Home | History | Annotate | Line # | Download | only in make
parse.c revision 1.691
      1 /*	$NetBSD: parse.c,v 1.691 2023/01/23 23:01:52 sjg Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1988, 1989, 1990, 1993
      5  *	The Regents of the University of California.  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) 1989 by Berkeley Softworks
     37  * All rights reserved.
     38  *
     39  * This code is derived from software contributed to Berkeley by
     40  * Adam de Boor.
     41  *
     42  * Redistribution and use in source and binary forms, with or without
     43  * modification, are permitted provided that the following conditions
     44  * are met:
     45  * 1. Redistributions of source code must retain the above copyright
     46  *    notice, this list of conditions and the following disclaimer.
     47  * 2. Redistributions in binary form must reproduce the above copyright
     48  *    notice, this list of conditions and the following disclaimer in the
     49  *    documentation and/or other materials provided with the distribution.
     50  * 3. All advertising materials mentioning features or use of this software
     51  *    must display the following acknowledgement:
     52  *	This product includes software developed by the University of
     53  *	California, Berkeley and its contributors.
     54  * 4. Neither the name of the University nor the names of its contributors
     55  *    may be used to endorse or promote products derived from this software
     56  *    without specific prior written permission.
     57  *
     58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     68  * SUCH DAMAGE.
     69  */
     70 
     71 /*
     72  * Parsing of makefiles.
     73  *
     74  * Parse_File is the main entry point and controls most of the other
     75  * functions in this module.
     76  *
     77  * Interface:
     78  *	Parse_Init	Initialize the module
     79  *
     80  *	Parse_End	Clean up the module
     81  *
     82  *	Parse_File	Parse a top-level makefile.  Included files are
     83  *			handled by IncludeFile instead.
     84  *
     85  *	Parse_VarAssign
     86  *			Try to parse the given line as a variable assignment.
     87  *			Used by MainParseArgs to determine if an argument is
     88  *			a target or a variable assignment.  Used internally
     89  *			for pretty much the same thing.
     90  *
     91  *	Parse_Error	Report a parse error, a warning or an informational
     92  *			message.
     93  *
     94  *	Parse_MainName	Returns a list of the single main target to create.
     95  */
     96 
     97 #include <sys/types.h>
     98 #include <sys/stat.h>
     99 #include <errno.h>
    100 #include <stdarg.h>
    101 
    102 #include "make.h"
    103 #include "dir.h"
    104 #include "job.h"
    105 #include "pathnames.h"
    106 
    107 /*	"@(#)parse.c	8.3 (Berkeley) 3/19/94"	*/
    108 MAKE_RCSID("$NetBSD: parse.c,v 1.691 2023/01/23 23:01:52 sjg Exp $");
    109 
    110 /*
    111  * A file being read.
    112  */
    113 typedef struct IncludedFile {
    114 	FStr name;		/* absolute or relative to the cwd */
    115 	unsigned lineno;	/* 1-based */
    116 	unsigned readLines;	/* the number of physical lines that have
    117 				 * been read from the file */
    118 	unsigned forHeadLineno;	/* 1-based */
    119 	unsigned forBodyReadLines; /* the number of physical lines that have
    120 				 * been read from the file above the body of
    121 				 * the .for loop */
    122 	unsigned int condMinDepth; /* depth of nested 'if' directives, at the
    123 				 * beginning of the file */
    124 	bool depending;		/* state of doing_depend on EOF */
    125 
    126 	Buffer buf;		/* the file's content or the body of the .for
    127 				 * loop; either empty or ends with '\n' */
    128 	char *buf_ptr;		/* next char to be read */
    129 	char *buf_end;		/* buf_end[-1] == '\n' */
    130 
    131 	struct ForLoop *forLoop;
    132 } IncludedFile;
    133 
    134 /* Special attributes for target nodes. */
    135 typedef enum ParseSpecial {
    136 	SP_ATTRIBUTE,	/* Generic attribute */
    137 	SP_BEGIN,	/* .BEGIN */
    138 	SP_DEFAULT,	/* .DEFAULT */
    139 	SP_DELETE_ON_ERROR, /* .DELETE_ON_ERROR */
    140 	SP_END,		/* .END */
    141 	SP_ERROR,	/* .ERROR */
    142 	SP_IGNORE,	/* .IGNORE */
    143 	SP_INCLUDES,	/* .INCLUDES; not mentioned in the manual page */
    144 	SP_INTERRUPT,	/* .INTERRUPT */
    145 	SP_LIBS,	/* .LIBS; not mentioned in the manual page */
    146 	SP_MAIN,	/* .MAIN and no user-specified targets to make */
    147 	SP_META,	/* .META */
    148 	SP_MFLAGS,	/* .MFLAGS or .MAKEFLAGS */
    149 	SP_NOMETA,	/* .NOMETA */
    150 	SP_NOMETA_CMP,	/* .NOMETA_CMP */
    151 	SP_NOPATH,	/* .NOPATH */
    152 	SP_NOREADONLY,	/* .NOREADONLY */
    153 	SP_NOT,		/* Not special */
    154 	SP_NOTPARALLEL,	/* .NOTPARALLEL or .NO_PARALLEL */
    155 	SP_NULL,	/* .NULL; not mentioned in the manual page */
    156 	SP_OBJDIR,	/* .OBJDIR */
    157 	SP_ORDER,	/* .ORDER */
    158 	SP_PARALLEL,	/* .PARALLEL; not mentioned in the manual page */
    159 	SP_PATH,	/* .PATH or .PATH.suffix */
    160 	SP_PHONY,	/* .PHONY */
    161 #ifdef POSIX
    162 	SP_POSIX,	/* .POSIX; not mentioned in the manual page */
    163 #endif
    164 	SP_PRECIOUS,	/* .PRECIOUS */
    165 	SP_READONLY,	/* .READONLY */
    166 	SP_SHELL,	/* .SHELL */
    167 	SP_SILENT,	/* .SILENT */
    168 	SP_SINGLESHELL,	/* .SINGLESHELL; not mentioned in the manual page */
    169 	SP_STALE,	/* .STALE */
    170 	SP_SUFFIXES,	/* .SUFFIXES */
    171 	SP_WAIT		/* .WAIT */
    172 } ParseSpecial;
    173 
    174 typedef List SearchPathList;
    175 typedef ListNode SearchPathListNode;
    176 
    177 
    178 typedef enum VarAssignOp {
    179 	VAR_NORMAL,		/* = */
    180 	VAR_APPEND,		/* += */
    181 	VAR_DEFAULT,		/* ?= */
    182 	VAR_SUBST,		/* := */
    183 	VAR_SHELL		/* != or :sh= */
    184 } VarAssignOp;
    185 
    186 typedef struct VarAssign {
    187 	char *varname;		/* unexpanded */
    188 	VarAssignOp op;
    189 	const char *value;	/* unexpanded */
    190 } VarAssign;
    191 
    192 static bool Parse_IsVar(const char *, VarAssign *);
    193 static void Parse_Var(VarAssign *, GNode *);
    194 
    195 /*
    196  * The target to be made if no targets are specified in the command line.
    197  * This is the first target defined in any of the makefiles.
    198  */
    199 GNode *mainNode;
    200 
    201 /*
    202  * During parsing, the targets from the left-hand side of the currently
    203  * active dependency line, or NULL if the current line does not belong to a
    204  * dependency line, for example because it is a variable assignment.
    205  *
    206  * See unit-tests/deptgt.mk, keyword "parse.c:targets".
    207  */
    208 static GNodeList *targets;
    209 
    210 #ifdef CLEANUP
    211 /*
    212  * All shell commands for all targets, in no particular order and possibly
    213  * with duplicates.  Kept in a separate list since the commands from .USE or
    214  * .USEBEFORE nodes are shared with other GNodes, thereby giving up the
    215  * easily understandable ownership over the allocated strings.
    216  */
    217 static StringList targCmds = LST_INIT;
    218 #endif
    219 
    220 /*
    221  * Predecessor node for handling .ORDER. Initialized to NULL when .ORDER
    222  * is seen, then set to each successive source on the line.
    223  */
    224 static GNode *order_pred;
    225 
    226 static int parseErrors = 0;
    227 
    228 /*
    229  * The include chain of makefiles.  At index 0 is the top-level makefile from
    230  * the command line, followed by the included files or .for loops, up to and
    231  * including the current file.
    232  *
    233  * See PrintStackTrace for how to interpret the data.
    234  */
    235 static Vector /* of IncludedFile */ includes;
    236 
    237 SearchPath *parseIncPath;	/* directories for "..." includes */
    238 SearchPath *sysIncPath;		/* directories for <...> includes */
    239 SearchPath *defSysIncPath;	/* default for sysIncPath */
    240 
    241 /*
    242  * The parseKeywords table is searched using binary search when deciding
    243  * if a target or source is special. The 'spec' field is the ParseSpecial
    244  * type of the keyword (SP_NOT if the keyword isn't special as a target) while
    245  * the 'op' field is the operator to apply to the list of targets if the
    246  * keyword is used as a source ("0" if the keyword isn't special as a source)
    247  */
    248 static const struct {
    249 	const char name[17];
    250 	ParseSpecial special;	/* when used as a target */
    251 	GNodeType targetAttr;	/* when used as a source */
    252 } parseKeywords[] = {
    253     { ".BEGIN",		SP_BEGIN,	OP_NONE },
    254     { ".DEFAULT",	SP_DEFAULT,	OP_NONE },
    255     { ".DELETE_ON_ERROR", SP_DELETE_ON_ERROR, OP_NONE },
    256     { ".END",		SP_END,		OP_NONE },
    257     { ".ERROR",		SP_ERROR,	OP_NONE },
    258     { ".EXEC",		SP_ATTRIBUTE,	OP_EXEC },
    259     { ".IGNORE",	SP_IGNORE,	OP_IGNORE },
    260     { ".INCLUDES",	SP_INCLUDES,	OP_NONE },
    261     { ".INTERRUPT",	SP_INTERRUPT,	OP_NONE },
    262     { ".INVISIBLE",	SP_ATTRIBUTE,	OP_INVISIBLE },
    263     { ".JOIN",		SP_ATTRIBUTE,	OP_JOIN },
    264     { ".LIBS",		SP_LIBS,	OP_NONE },
    265     { ".MADE",		SP_ATTRIBUTE,	OP_MADE },
    266     { ".MAIN",		SP_MAIN,	OP_NONE },
    267     { ".MAKE",		SP_ATTRIBUTE,	OP_MAKE },
    268     { ".MAKEFLAGS",	SP_MFLAGS,	OP_NONE },
    269     { ".META",		SP_META,	OP_META },
    270     { ".MFLAGS",	SP_MFLAGS,	OP_NONE },
    271     { ".NOMETA",	SP_NOMETA,	OP_NOMETA },
    272     { ".NOMETA_CMP",	SP_NOMETA_CMP,	OP_NOMETA_CMP },
    273     { ".NOPATH",	SP_NOPATH,	OP_NOPATH },
    274     { ".NOREADONLY",	SP_NOREADONLY,	OP_NONE },
    275     { ".NOTMAIN",	SP_ATTRIBUTE,	OP_NOTMAIN },
    276     { ".NOTPARALLEL",	SP_NOTPARALLEL,	OP_NONE },
    277     { ".NO_PARALLEL",	SP_NOTPARALLEL,	OP_NONE },
    278     { ".NULL",		SP_NULL,	OP_NONE },
    279     { ".OBJDIR",	SP_OBJDIR,	OP_NONE },
    280     { ".OPTIONAL",	SP_ATTRIBUTE,	OP_OPTIONAL },
    281     { ".ORDER",		SP_ORDER,	OP_NONE },
    282     { ".PARALLEL",	SP_PARALLEL,	OP_NONE },
    283     { ".PATH",		SP_PATH,	OP_NONE },
    284     { ".PHONY",		SP_PHONY,	OP_PHONY },
    285 #ifdef POSIX
    286     { ".POSIX",		SP_POSIX,	OP_NONE },
    287 #endif
    288     { ".PRECIOUS",	SP_PRECIOUS,	OP_PRECIOUS },
    289     { ".READONLY",	SP_READONLY,	OP_NONE },
    290     { ".RECURSIVE",	SP_ATTRIBUTE,	OP_MAKE },
    291     { ".SHELL",		SP_SHELL,	OP_NONE },
    292     { ".SILENT",	SP_SILENT,	OP_SILENT },
    293     { ".SINGLESHELL",	SP_SINGLESHELL,	OP_NONE },
    294     { ".STALE",		SP_STALE,	OP_NONE },
    295     { ".SUFFIXES",	SP_SUFFIXES,	OP_NONE },
    296     { ".USE",		SP_ATTRIBUTE,	OP_USE },
    297     { ".USEBEFORE",	SP_ATTRIBUTE,	OP_USEBEFORE },
    298     { ".WAIT",		SP_WAIT,	OP_NONE },
    299 };
    300 
    301 enum PosixState posix_state = PS_NOT_YET;
    302 
    303 static IncludedFile *
    304 GetInclude(size_t i)
    305 {
    306 	assert(i < includes.len);
    307 	return Vector_Get(&includes, i);
    308 }
    309 
    310 /* The file that is currently being read. */
    311 static IncludedFile *
    312 CurFile(void)
    313 {
    314 	return GetInclude(includes.len - 1);
    315 }
    316 
    317 unsigned int
    318 CurFile_CondMinDepth(void)
    319 {
    320 	return CurFile()->condMinDepth;
    321 }
    322 
    323 static Buffer
    324 LoadFile(const char *path, int fd)
    325 {
    326 	ssize_t n;
    327 	Buffer buf;
    328 	size_t bufSize;
    329 	struct stat st;
    330 
    331 	bufSize = fstat(fd, &st) == 0 && S_ISREG(st.st_mode) &&
    332 		  st.st_size > 0 && st.st_size < 1024 * 1024 * 1024
    333 	    ? (size_t)st.st_size : 1024;
    334 	Buf_InitSize(&buf, bufSize);
    335 
    336 	for (;;) {
    337 		if (buf.len == buf.cap) {
    338 			if (buf.cap >= 512 * 1024 * 1024) {
    339 				Error("%s: file too large", path);
    340 				exit(2); /* Not 1 so -q can distinguish error */
    341 			}
    342 			Buf_Expand(&buf);
    343 		}
    344 		assert(buf.len < buf.cap);
    345 		n = read(fd, buf.data + buf.len, buf.cap - buf.len);
    346 		if (n < 0) {
    347 			Error("%s: read error: %s", path, strerror(errno));
    348 			exit(2);	/* Not 1 so -q can distinguish error */
    349 		}
    350 		if (n == 0)
    351 			break;
    352 
    353 		buf.len += (size_t)n;
    354 	}
    355 	assert(buf.len <= buf.cap);
    356 
    357 	if (!Buf_EndsWith(&buf, '\n'))
    358 		Buf_AddByte(&buf, '\n');
    359 
    360 	return buf;		/* may not be null-terminated */
    361 }
    362 
    363 /*
    364  * Print the current chain of .include and .for directives.  In Parse_Fatal
    365  * or other functions that already print the location, includingInnermost
    366  * would be redundant, but in other cases like Error or Fatal it needs to be
    367  * included.
    368  */
    369 void
    370 PrintStackTrace(bool includingInnermost)
    371 {
    372 	const IncludedFile *entries;
    373 	size_t i, n;
    374 
    375 	n = includes.len;
    376 	if (n == 0)
    377 		return;
    378 
    379 	entries = GetInclude(0);
    380 	if (!includingInnermost && entries[n - 1].forLoop == NULL)
    381 		n--;		/* already in the diagnostic */
    382 
    383 	for (i = n; i-- > 0;) {
    384 		const IncludedFile *entry = entries + i;
    385 		const char *fname = entry->name.str;
    386 		char dirbuf[MAXPATHLEN + 1];
    387 
    388 		if (fname[0] != '/' && strcmp(fname, "(stdin)") != 0)
    389 			fname = realpath(fname, dirbuf);
    390 
    391 		if (entry->forLoop != NULL) {
    392 			char *details = ForLoop_Details(entry->forLoop);
    393 			debug_printf("\tin .for loop from %s:%u with %s\n",
    394 			    fname, entry->forHeadLineno, details);
    395 			free(details);
    396 		} else if (i + 1 < n && entries[i + 1].forLoop != NULL) {
    397 			/* entry->lineno is not a useful line number */
    398 		} else
    399 			debug_printf("\tin %s:%u\n", fname, entry->lineno);
    400 	}
    401 }
    402 
    403 /* Check if the current character is escaped on the current line. */
    404 static bool
    405 IsEscaped(const char *line, const char *p)
    406 {
    407 	bool escaped = false;
    408 	while (p > line && *--p == '\\')
    409 		escaped = !escaped;
    410 	return escaped;
    411 }
    412 
    413 /*
    414  * Add the filename and lineno to the GNode so that we remember where it
    415  * was first defined.
    416  */
    417 static void
    418 RememberLocation(GNode *gn)
    419 {
    420 	IncludedFile *curFile = CurFile();
    421 	gn->fname = Str_Intern(curFile->name.str);
    422 	gn->lineno = curFile->lineno;
    423 }
    424 
    425 /*
    426  * Look in the table of keywords for one matching the given string.
    427  * Return the index of the keyword, or -1 if it isn't there.
    428  */
    429 static int
    430 FindKeyword(const char *str)
    431 {
    432 	int start = 0;
    433 	int end = sizeof parseKeywords / sizeof parseKeywords[0] - 1;
    434 
    435 	while (start <= end) {
    436 		int curr = start + (end - start) / 2;
    437 		int diff = strcmp(str, parseKeywords[curr].name);
    438 
    439 		if (diff == 0)
    440 			return curr;
    441 		if (diff < 0)
    442 			end = curr - 1;
    443 		else
    444 			start = curr + 1;
    445 	}
    446 
    447 	return -1;
    448 }
    449 
    450 void
    451 PrintLocation(FILE *f, bool useVars, const GNode *gn)
    452 {
    453 	char dirbuf[MAXPATHLEN + 1];
    454 	FStr dir, base;
    455 	const char *fname;
    456 	unsigned lineno;
    457 
    458 	if (gn != NULL) {
    459 		fname = gn->fname;
    460 		lineno = gn->lineno;
    461 	} else if (includes.len > 0) {
    462 		IncludedFile *curFile = CurFile();
    463 		fname = curFile->name.str;
    464 		lineno = curFile->lineno;
    465 	} else
    466 		return;
    467 
    468 	if (!useVars || fname[0] == '/' || strcmp(fname, "(stdin)") == 0) {
    469 		(void)fprintf(f, "\"%s\" line %u: ", fname, lineno);
    470 		return;
    471 	}
    472 
    473 	dir = Var_Value(SCOPE_GLOBAL, ".PARSEDIR");
    474 	if (dir.str == NULL)
    475 		dir.str = ".";
    476 	if (dir.str[0] != '/')
    477 		dir.str = realpath(dir.str, dirbuf);
    478 
    479 	base = Var_Value(SCOPE_GLOBAL, ".PARSEFILE");
    480 	if (base.str == NULL)
    481 		base.str = str_basename(fname);
    482 
    483 	(void)fprintf(f, "\"%s/%s\" line %u: ", dir.str, base.str, lineno);
    484 
    485 	FStr_Done(&base);
    486 	FStr_Done(&dir);
    487 }
    488 
    489 static void MAKE_ATTR_PRINTFLIKE(5, 0)
    490 ParseVErrorInternal(FILE *f, bool useVars, const GNode *gn,
    491 		    ParseErrorLevel level, const char *fmt, va_list ap)
    492 {
    493 	static bool fatal_warning_error_printed = false;
    494 
    495 	(void)fprintf(f, "%s: ", progname);
    496 
    497 	PrintLocation(f, useVars, gn);
    498 	if (level == PARSE_WARNING)
    499 		(void)fprintf(f, "warning: ");
    500 	(void)vfprintf(f, fmt, ap);
    501 	(void)fprintf(f, "\n");
    502 	(void)fflush(f);
    503 
    504 	if (level == PARSE_FATAL)
    505 		parseErrors++;
    506 	if (level == PARSE_WARNING && opts.parseWarnFatal) {
    507 		if (!fatal_warning_error_printed) {
    508 			Error("parsing warnings being treated as errors");
    509 			fatal_warning_error_printed = true;
    510 		}
    511 		parseErrors++;
    512 	}
    513 
    514 	if (DEBUG(PARSE))
    515 		PrintStackTrace(false);
    516 }
    517 
    518 static void MAKE_ATTR_PRINTFLIKE(3, 4)
    519 ParseErrorInternal(const GNode *gn,
    520 		   ParseErrorLevel level, const char *fmt, ...)
    521 {
    522 	va_list ap;
    523 
    524 	(void)fflush(stdout);
    525 	va_start(ap, fmt);
    526 	ParseVErrorInternal(stderr, false, gn, level, fmt, ap);
    527 	va_end(ap);
    528 
    529 	if (opts.debug_file != stdout && opts.debug_file != stderr) {
    530 		va_start(ap, fmt);
    531 		ParseVErrorInternal(opts.debug_file, false, gn,
    532 		    level, fmt, ap);
    533 		va_end(ap);
    534 	}
    535 }
    536 
    537 /*
    538  * Print a parse error message, including location information.
    539  *
    540  * If the level is PARSE_FATAL, continue parsing until the end of the
    541  * current top-level makefile, then exit (see Parse_File).
    542  *
    543  * Fmt is given without a trailing newline.
    544  */
    545 void
    546 Parse_Error(ParseErrorLevel level, const char *fmt, ...)
    547 {
    548 	va_list ap;
    549 
    550 	(void)fflush(stdout);
    551 	va_start(ap, fmt);
    552 	ParseVErrorInternal(stderr, true, NULL, level, fmt, ap);
    553 	va_end(ap);
    554 
    555 	if (opts.debug_file != stdout && opts.debug_file != stderr) {
    556 		va_start(ap, fmt);
    557 		ParseVErrorInternal(opts.debug_file, true, NULL,
    558 		    level, fmt, ap);
    559 		va_end(ap);
    560 	}
    561 }
    562 
    563 
    564 /*
    565  * Handle an .info, .warning or .error directive.  For an .error directive,
    566  * exit immediately.
    567  */
    568 static void
    569 HandleMessage(ParseErrorLevel level, const char *levelName, const char *umsg)
    570 {
    571 	char *xmsg;
    572 
    573 	if (umsg[0] == '\0') {
    574 		Parse_Error(PARSE_FATAL, "Missing argument for \".%s\"",
    575 		    levelName);
    576 		return;
    577 	}
    578 
    579 	(void)Var_Subst(umsg, SCOPE_CMDLINE, VARE_WANTRES, &xmsg);
    580 	/* TODO: handle errors */
    581 
    582 	Parse_Error(level, "%s", xmsg);
    583 	free(xmsg);
    584 
    585 	if (level == PARSE_FATAL) {
    586 		PrintOnError(NULL, "\n");
    587 		exit(1);
    588 	}
    589 }
    590 
    591 /*
    592  * Add the child to the parent's children, and for non-special targets, vice
    593  * versa.  Special targets such as .END do not need to be informed once the
    594  * child target has been made.
    595  */
    596 static void
    597 LinkSource(GNode *pgn, GNode *cgn, bool isSpecial)
    598 {
    599 	if ((pgn->type & OP_DOUBLEDEP) && !Lst_IsEmpty(&pgn->cohorts))
    600 		pgn = pgn->cohorts.last->datum;
    601 
    602 	Lst_Append(&pgn->children, cgn);
    603 	pgn->unmade++;
    604 
    605 	/* Special targets like .END don't need any children. */
    606 	if (!isSpecial)
    607 		Lst_Append(&cgn->parents, pgn);
    608 
    609 	if (DEBUG(PARSE)) {
    610 		debug_printf("# LinkSource: added child %s - %s\n",
    611 		    pgn->name, cgn->name);
    612 		Targ_PrintNode(pgn, 0);
    613 		Targ_PrintNode(cgn, 0);
    614 	}
    615 }
    616 
    617 /* Add the node to each target from the current dependency group. */
    618 static void
    619 LinkToTargets(GNode *gn, bool isSpecial)
    620 {
    621 	GNodeListNode *ln;
    622 
    623 	for (ln = targets->first; ln != NULL; ln = ln->next)
    624 		LinkSource(ln->datum, gn, isSpecial);
    625 }
    626 
    627 static bool
    628 TryApplyDependencyOperator(GNode *gn, GNodeType op)
    629 {
    630 	/*
    631 	 * If the node occurred on the left-hand side of a dependency and the
    632 	 * operator also defines a dependency, they must match.
    633 	 */
    634 	if ((op & OP_OPMASK) && (gn->type & OP_OPMASK) &&
    635 	    ((op & OP_OPMASK) != (gn->type & OP_OPMASK))) {
    636 		Parse_Error(PARSE_FATAL, "Inconsistent operator for %s",
    637 		    gn->name);
    638 		return false;
    639 	}
    640 
    641 	if (op == OP_DOUBLEDEP && (gn->type & OP_OPMASK) == OP_DOUBLEDEP) {
    642 		/*
    643 		 * If the node was of the left-hand side of a '::' operator,
    644 		 * we need to create a new instance of it for the children
    645 		 * and commands on this dependency line since each of these
    646 		 * dependency groups has its own attributes and commands,
    647 		 * separate from the others.
    648 		 *
    649 		 * The new instance is placed on the 'cohorts' list of the
    650 		 * initial one (note the initial one is not on its own
    651 		 * cohorts list) and the new instance is linked to all
    652 		 * parents of the initial instance.
    653 		 */
    654 		GNode *cohort;
    655 
    656 		/*
    657 		 * Propagate copied bits to the initial node.  They'll be
    658 		 * propagated back to the rest of the cohorts later.
    659 		 */
    660 		gn->type |= op & (unsigned)~OP_OPMASK;
    661 
    662 		cohort = Targ_NewInternalNode(gn->name);
    663 		if (doing_depend)
    664 			RememberLocation(cohort);
    665 		/*
    666 		 * Make the cohort invisible as well to avoid duplicating it
    667 		 * into other variables. True, parents of this target won't
    668 		 * tend to do anything with their local variables, but better
    669 		 * safe than sorry.
    670 		 *
    671 		 * (I think this is pointless now, since the relevant list
    672 		 * traversals will no longer see this node anyway. -mycroft)
    673 		 */
    674 		cohort->type = op | OP_INVISIBLE;
    675 		Lst_Append(&gn->cohorts, cohort);
    676 		cohort->centurion = gn;
    677 		gn->unmade_cohorts++;
    678 		snprintf(cohort->cohort_num, sizeof cohort->cohort_num, "#%d",
    679 		    (unsigned int)gn->unmade_cohorts % 1000000);
    680 	} else {
    681 		/*
    682 		 * We don't want to nuke any previous flags (whatever they
    683 		 * were) so we just OR the new operator into the old.
    684 		 */
    685 		gn->type |= op;
    686 	}
    687 
    688 	return true;
    689 }
    690 
    691 static void
    692 ApplyDependencyOperator(GNodeType op)
    693 {
    694 	GNodeListNode *ln;
    695 
    696 	for (ln = targets->first; ln != NULL; ln = ln->next)
    697 		if (!TryApplyDependencyOperator(ln->datum, op))
    698 			break;
    699 }
    700 
    701 /*
    702  * We add a .WAIT node in the dependency list. After any dynamic dependencies
    703  * (and filename globbing) have happened, it is given a dependency on each
    704  * previous child, back until the previous .WAIT node. The next child won't
    705  * be scheduled until the .WAIT node is built.
    706  *
    707  * We give each .WAIT node a unique name (mainly for diagnostics).
    708  */
    709 static void
    710 ApplyDependencySourceWait(bool isSpecial)
    711 {
    712 	static unsigned wait_number = 0;
    713 	char name[6 + 10 + 1];
    714 	GNode *gn;
    715 
    716 	snprintf(name, sizeof name, ".WAIT_%u", ++wait_number);
    717 	gn = Targ_NewInternalNode(name);
    718 	if (doing_depend)
    719 		RememberLocation(gn);
    720 	gn->type = OP_WAIT | OP_PHONY | OP_DEPENDS | OP_NOTMAIN;
    721 	LinkToTargets(gn, isSpecial);
    722 }
    723 
    724 static bool
    725 ApplyDependencySourceKeyword(const char *src, ParseSpecial special)
    726 {
    727 	int keywd;
    728 	GNodeType targetAttr;
    729 
    730 	if (*src != '.' || !ch_isupper(src[1]))
    731 		return false;
    732 
    733 	keywd = FindKeyword(src);
    734 	if (keywd == -1)
    735 		return false;
    736 
    737 	targetAttr = parseKeywords[keywd].targetAttr;
    738 	if (targetAttr != OP_NONE) {
    739 		ApplyDependencyOperator(targetAttr);
    740 		return true;
    741 	}
    742 	if (parseKeywords[keywd].special == SP_WAIT) {
    743 		ApplyDependencySourceWait(special != SP_NOT);
    744 		return true;
    745 	}
    746 	return false;
    747 }
    748 
    749 /*
    750  * In a line like ".MAIN: source1 source2", add all sources to the list of
    751  * things to create, but only if the user didn't specify a target on the
    752  * command line and .MAIN occurs for the first time.
    753  *
    754  * See HandleDependencyTargetSpecial, branch SP_MAIN.
    755  * See unit-tests/cond-func-make-main.mk.
    756  */
    757 static void
    758 ApplyDependencySourceMain(const char *src)
    759 {
    760 	Lst_Append(&opts.create, bmake_strdup(src));
    761 	/*
    762 	 * Add the name to the .TARGETS variable as well, so the user can
    763 	 * employ that, if desired.
    764 	 */
    765 	Global_Append(".TARGETS", src);
    766 }
    767 
    768 /*
    769  * For the sources of a .ORDER target, create predecessor/successor links
    770  * between the previous source and the current one.
    771  */
    772 static void
    773 ApplyDependencySourceOrder(const char *src)
    774 {
    775 	GNode *gn;
    776 
    777 	gn = Targ_GetNode(src);
    778 	if (doing_depend)
    779 		RememberLocation(gn);
    780 	if (order_pred != NULL) {
    781 		Lst_Append(&order_pred->order_succ, gn);
    782 		Lst_Append(&gn->order_pred, order_pred);
    783 		if (DEBUG(PARSE)) {
    784 			debug_printf(
    785 			    "# .ORDER forces '%s' to be made before '%s'\n",
    786 			    order_pred->name, gn->name);
    787 			Targ_PrintNode(order_pred, 0);
    788 			Targ_PrintNode(gn, 0);
    789 		}
    790 	}
    791 	/*
    792 	 * The current source now becomes the predecessor for the next one.
    793 	 */
    794 	order_pred = gn;
    795 }
    796 
    797 /* The source is not an attribute, so find/create a node for it. */
    798 static void
    799 ApplyDependencySourceOther(const char *src, GNodeType targetAttr,
    800 			   ParseSpecial special)
    801 {
    802 	GNode *gn;
    803 
    804 	gn = Targ_GetNode(src);
    805 	if (doing_depend)
    806 		RememberLocation(gn);
    807 	if (targetAttr != OP_NONE)
    808 		gn->type |= targetAttr;
    809 	else
    810 		LinkToTargets(gn, special != SP_NOT);
    811 }
    812 
    813 /*
    814  * Given the name of a source in a dependency line, figure out if it is an
    815  * attribute (such as .SILENT) and if so, apply it to all targets. Otherwise
    816  * decide if there is some attribute which should be applied *to* the source
    817  * because of some special target (such as .PHONY) and apply it if so.
    818  * Otherwise, make the source a child of the targets.
    819  */
    820 static void
    821 ApplyDependencySource(GNodeType targetAttr, const char *src,
    822 		      ParseSpecial special)
    823 {
    824 	if (ApplyDependencySourceKeyword(src, special))
    825 		return;
    826 
    827 	if (special == SP_MAIN)
    828 		ApplyDependencySourceMain(src);
    829 	else if (special == SP_ORDER)
    830 		ApplyDependencySourceOrder(src);
    831 	else
    832 		ApplyDependencySourceOther(src, targetAttr, special);
    833 }
    834 
    835 /*
    836  * If we have yet to decide on a main target to make, in the absence of any
    837  * user input, we want the first target on the first dependency line that is
    838  * actually a real target (i.e. isn't a .USE or .EXEC rule) to be made.
    839  */
    840 static void
    841 MaybeUpdateMainTarget(void)
    842 {
    843 	GNodeListNode *ln;
    844 
    845 	if (mainNode != NULL)
    846 		return;
    847 
    848 	for (ln = targets->first; ln != NULL; ln = ln->next) {
    849 		GNode *gn = ln->datum;
    850 		if (GNode_IsMainCandidate(gn)) {
    851 			DEBUG1(MAKE, "Setting main node to \"%s\"\n", gn->name);
    852 			mainNode = gn;
    853 			return;
    854 		}
    855 	}
    856 }
    857 
    858 static void
    859 InvalidLineType(const char *line)
    860 {
    861 	if (strncmp(line, "<<<<<<", 6) == 0 ||
    862 	    strncmp(line, ">>>>>>", 6) == 0)
    863 		Parse_Error(PARSE_FATAL,
    864 		    "Makefile appears to contain unresolved CVS/RCS/??? merge conflicts");
    865 	else if (line[0] == '.') {
    866 		const char *dirstart = line + 1;
    867 		const char *dirend;
    868 		cpp_skip_whitespace(&dirstart);
    869 		dirend = dirstart;
    870 		while (ch_isalnum(*dirend) || *dirend == '-')
    871 			dirend++;
    872 		Parse_Error(PARSE_FATAL, "Unknown directive \"%.*s\"",
    873 		    (int)(dirend - dirstart), dirstart);
    874 	} else
    875 		Parse_Error(PARSE_FATAL, "Invalid line type");
    876 }
    877 
    878 static void
    879 ParseDependencyTargetWord(char **pp, const char *lstart)
    880 {
    881 	const char *cp = *pp;
    882 
    883 	while (*cp != '\0') {
    884 		if ((ch_isspace(*cp) || *cp == '!' || *cp == ':' ||
    885 		     *cp == '(') &&
    886 		    !IsEscaped(lstart, cp))
    887 			break;
    888 
    889 		if (*cp == '$') {
    890 			/*
    891 			 * Must be a dynamic source (would have been expanded
    892 			 * otherwise).
    893 			 *
    894 			 * There should be no errors in this, as they would
    895 			 * have been discovered in the initial Var_Subst and
    896 			 * we wouldn't be here.
    897 			 */
    898 			FStr val;
    899 
    900 			(void)Var_Parse(&cp, SCOPE_CMDLINE,
    901 			    VARE_PARSE_ONLY, &val);
    902 			FStr_Done(&val);
    903 		} else
    904 			cp++;
    905 	}
    906 
    907 	*pp += cp - *pp;
    908 }
    909 
    910 /*
    911  * Handle special targets like .PATH, .DEFAULT, .BEGIN, .ORDER.
    912  *
    913  * See the tests deptgt-*.mk.
    914  */
    915 static void
    916 HandleDependencyTargetSpecial(const char *targetName,
    917 			      ParseSpecial *inout_special,
    918 			      SearchPathList **inout_paths)
    919 {
    920 	switch (*inout_special) {
    921 	case SP_PATH:
    922 		if (*inout_paths == NULL)
    923 			*inout_paths = Lst_New();
    924 		Lst_Append(*inout_paths, &dirSearchPath);
    925 		break;
    926 	case SP_MAIN:
    927 		/*
    928 		 * Allow targets from the command line to override the
    929 		 * .MAIN node.
    930 		 */
    931 		if (!Lst_IsEmpty(&opts.create))
    932 			*inout_special = SP_NOT;
    933 		break;
    934 	case SP_BEGIN:
    935 	case SP_END:
    936 	case SP_STALE:
    937 	case SP_ERROR:
    938 	case SP_INTERRUPT: {
    939 		GNode *gn = Targ_GetNode(targetName);
    940 		if (doing_depend)
    941 			RememberLocation(gn);
    942 		gn->type |= OP_NOTMAIN | OP_SPECIAL;
    943 		Lst_Append(targets, gn);
    944 		break;
    945 	}
    946 	case SP_DEFAULT: {
    947 		/*
    948 		 * Need to create a node to hang commands on, but we don't
    949 		 * want it in the graph, nor do we want it to be the Main
    950 		 * Target. We claim the node is a transformation rule to make
    951 		 * life easier later, when we'll use Make_HandleUse to
    952 		 * actually apply the .DEFAULT commands.
    953 		 */
    954 		GNode *gn = GNode_New(".DEFAULT");
    955 		gn->type |= OP_NOTMAIN | OP_TRANSFORM;
    956 		Lst_Append(targets, gn);
    957 		defaultNode = gn;
    958 		break;
    959 	}
    960 	case SP_DELETE_ON_ERROR:
    961 		deleteOnError = true;
    962 		break;
    963 	case SP_NOTPARALLEL:
    964 		opts.maxJobs = 1;
    965 		break;
    966 	case SP_SINGLESHELL:
    967 		opts.compatMake = true;
    968 		break;
    969 	case SP_ORDER:
    970 		order_pred = NULL;
    971 		break;
    972 	default:
    973 		break;
    974 	}
    975 }
    976 
    977 static bool
    978 HandleDependencyTargetPath(const char *suffixName,
    979 			   SearchPathList **inout_paths)
    980 {
    981 	SearchPath *path;
    982 
    983 	path = Suff_GetPath(suffixName);
    984 	if (path == NULL) {
    985 		Parse_Error(PARSE_FATAL,
    986 		    "Suffix '%s' not defined (yet)", suffixName);
    987 		return false;
    988 	}
    989 
    990 	if (*inout_paths == NULL)
    991 		*inout_paths = Lst_New();
    992 	Lst_Append(*inout_paths, path);
    993 
    994 	return true;
    995 }
    996 
    997 /* See if it's a special target and if so set inout_special to match it. */
    998 static bool
    999 HandleDependencyTarget(const char *targetName,
   1000 		       ParseSpecial *inout_special,
   1001 		       GNodeType *inout_targetAttr,
   1002 		       SearchPathList **inout_paths)
   1003 {
   1004 	int keywd;
   1005 
   1006 	if (!(targetName[0] == '.' && ch_isupper(targetName[1])))
   1007 		return true;
   1008 
   1009 	/*
   1010 	 * See if the target is a special target that must have it
   1011 	 * or its sources handled specially.
   1012 	 */
   1013 	keywd = FindKeyword(targetName);
   1014 	if (keywd != -1) {
   1015 		if (*inout_special == SP_PATH &&
   1016 		    parseKeywords[keywd].special != SP_PATH) {
   1017 			Parse_Error(PARSE_FATAL, "Mismatched special targets");
   1018 			return false;
   1019 		}
   1020 
   1021 		*inout_special = parseKeywords[keywd].special;
   1022 		*inout_targetAttr = parseKeywords[keywd].targetAttr;
   1023 
   1024 		HandleDependencyTargetSpecial(targetName, inout_special,
   1025 		    inout_paths);
   1026 
   1027 	} else if (strncmp(targetName, ".PATH", 5) == 0) {
   1028 		*inout_special = SP_PATH;
   1029 		if (!HandleDependencyTargetPath(targetName + 5, inout_paths))
   1030 			return false;
   1031 	}
   1032 	return true;
   1033 }
   1034 
   1035 static void
   1036 HandleSingleDependencyTargetMundane(const char *name)
   1037 {
   1038 	GNode *gn = Suff_IsTransform(name)
   1039 	    ? Suff_AddTransform(name)
   1040 	    : Targ_GetNode(name);
   1041 	if (doing_depend)
   1042 		RememberLocation(gn);
   1043 
   1044 	Lst_Append(targets, gn);
   1045 }
   1046 
   1047 static void
   1048 HandleDependencyTargetMundane(const char *targetName)
   1049 {
   1050 	if (Dir_HasWildcards(targetName)) {
   1051 		StringList targetNames = LST_INIT;
   1052 
   1053 		SearchPath *emptyPath = SearchPath_New();
   1054 		SearchPath_Expand(emptyPath, targetName, &targetNames);
   1055 		SearchPath_Free(emptyPath);
   1056 
   1057 		while (!Lst_IsEmpty(&targetNames)) {
   1058 			char *targName = Lst_Dequeue(&targetNames);
   1059 			HandleSingleDependencyTargetMundane(targName);
   1060 			free(targName);
   1061 		}
   1062 	} else
   1063 		HandleSingleDependencyTargetMundane(targetName);
   1064 }
   1065 
   1066 static void
   1067 SkipExtraTargets(char **pp, const char *lstart)
   1068 {
   1069 	bool warning = false;
   1070 	const char *p = *pp;
   1071 
   1072 	while (*p != '\0') {
   1073 		if (!IsEscaped(lstart, p) && (*p == '!' || *p == ':'))
   1074 			break;
   1075 		if (IsEscaped(lstart, p) || (*p != ' ' && *p != '\t'))
   1076 			warning = true;
   1077 		p++;
   1078 	}
   1079 	if (warning) {
   1080 		const char *start = *pp;
   1081 		cpp_skip_whitespace(&start);
   1082 		Parse_Error(PARSE_WARNING, "Extra target '%.*s' ignored",
   1083 		    (int)(p - start), start);
   1084 	}
   1085 
   1086 	*pp += p - *pp;
   1087 }
   1088 
   1089 static void
   1090 CheckSpecialMundaneMixture(ParseSpecial special)
   1091 {
   1092 	switch (special) {
   1093 	case SP_DEFAULT:
   1094 	case SP_STALE:
   1095 	case SP_BEGIN:
   1096 	case SP_END:
   1097 	case SP_ERROR:
   1098 	case SP_INTERRUPT:
   1099 		/*
   1100 		 * These create nodes on which to hang commands, so targets
   1101 		 * shouldn't be empty.
   1102 		 */
   1103 	case SP_NOT:
   1104 		/* Nothing special here -- targets may be empty. */
   1105 		break;
   1106 	default:
   1107 		Parse_Error(PARSE_WARNING,
   1108 		    "Special and mundane targets don't mix. "
   1109 		    "Mundane ones ignored");
   1110 		break;
   1111 	}
   1112 }
   1113 
   1114 /*
   1115  * In a dependency line like 'targets: sources' or 'targets! sources', parse
   1116  * the operator ':', '::' or '!' from between the targets and the sources.
   1117  */
   1118 static GNodeType
   1119 ParseDependencyOp(char **pp)
   1120 {
   1121 	if (**pp == '!')
   1122 		return (*pp)++, OP_FORCE;
   1123 	if (**pp == ':' && (*pp)[1] == ':')
   1124 		return *pp += 2, OP_DOUBLEDEP;
   1125 	else if (**pp == ':')
   1126 		return (*pp)++, OP_DEPENDS;
   1127 	else
   1128 		return OP_NONE;
   1129 }
   1130 
   1131 static void
   1132 ClearPaths(SearchPathList *paths)
   1133 {
   1134 	if (paths != NULL) {
   1135 		SearchPathListNode *ln;
   1136 		for (ln = paths->first; ln != NULL; ln = ln->next)
   1137 			SearchPath_Clear(ln->datum);
   1138 	}
   1139 
   1140 	Dir_SetPATH();
   1141 }
   1142 
   1143 static char *
   1144 FindInDirOfIncludingFile(const char *file)
   1145 {
   1146 	char *fullname, *incdir, *slash, *newName;
   1147 	int i;
   1148 
   1149 	fullname = NULL;
   1150 	incdir = bmake_strdup(CurFile()->name.str);
   1151 	slash = strrchr(incdir, '/');
   1152 	if (slash != NULL) {
   1153 		*slash = '\0';
   1154 		/*
   1155 		 * Now do lexical processing of leading "../" on the
   1156 		 * filename.
   1157 		 */
   1158 		for (i = 0; strncmp(file + i, "../", 3) == 0; i += 3) {
   1159 			slash = strrchr(incdir + 1, '/');
   1160 			if (slash == NULL || strcmp(slash, "/..") == 0)
   1161 				break;
   1162 			*slash = '\0';
   1163 		}
   1164 		newName = str_concat3(incdir, "/", file + i);
   1165 		fullname = Dir_FindFile(newName, parseIncPath);
   1166 		if (fullname == NULL)
   1167 			fullname = Dir_FindFile(newName, &dirSearchPath);
   1168 		free(newName);
   1169 	}
   1170 	free(incdir);
   1171 	return fullname;
   1172 }
   1173 
   1174 static char *
   1175 FindInQuotPath(const char *file)
   1176 {
   1177 	const char *suff;
   1178 	SearchPath *suffPath;
   1179 	char *fullname;
   1180 
   1181 	fullname = FindInDirOfIncludingFile(file);
   1182 	if (fullname == NULL &&
   1183 	    (suff = strrchr(file, '.')) != NULL &&
   1184 	    (suffPath = Suff_GetPath(suff)) != NULL)
   1185 		fullname = Dir_FindFile(file, suffPath);
   1186 	if (fullname == NULL)
   1187 		fullname = Dir_FindFile(file, parseIncPath);
   1188 	if (fullname == NULL)
   1189 		fullname = Dir_FindFile(file, &dirSearchPath);
   1190 	return fullname;
   1191 }
   1192 
   1193 /*
   1194  * Handle one of the .[-ds]include directives by remembering the current file
   1195  * and pushing the included file on the stack.  After the included file has
   1196  * finished, parsing continues with the including file; see Parse_PushInput
   1197  * and ParseEOF.
   1198  *
   1199  * System includes are looked up in sysIncPath, any other includes are looked
   1200  * up in the parsedir and then in the directories specified by the -I command
   1201  * line options.
   1202  */
   1203 static void
   1204 IncludeFile(const char *file, bool isSystem, bool depinc, bool silent)
   1205 {
   1206 	Buffer buf;
   1207 	char *fullname;		/* full pathname of file */
   1208 	int fd;
   1209 
   1210 	fullname = file[0] == '/' ? bmake_strdup(file) : NULL;
   1211 
   1212 	if (fullname == NULL && !isSystem)
   1213 		fullname = FindInQuotPath(file);
   1214 
   1215 	if (fullname == NULL) {
   1216 		SearchPath *path = Lst_IsEmpty(&sysIncPath->dirs)
   1217 		    ? defSysIncPath : sysIncPath;
   1218 		fullname = Dir_FindFile(file, path);
   1219 	}
   1220 
   1221 	if (fullname == NULL) {
   1222 		if (!silent)
   1223 			Parse_Error(PARSE_FATAL, "Could not find %s", file);
   1224 		return;
   1225 	}
   1226 
   1227 	if ((fd = open(fullname, O_RDONLY)) == -1) {
   1228 		if (!silent)
   1229 			Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
   1230 		free(fullname);
   1231 		return;
   1232 	}
   1233 
   1234 	buf = LoadFile(fullname, fd);
   1235 	(void)close(fd);
   1236 
   1237 	Parse_PushInput(fullname, 1, 0, buf, NULL);
   1238 	if (depinc)
   1239 		doing_depend = depinc;	/* only turn it on */
   1240 	free(fullname);
   1241 }
   1242 
   1243 /* Handle a "dependency" line like '.SPECIAL:' without any sources. */
   1244 static void
   1245 HandleDependencySourcesEmpty(ParseSpecial special, SearchPathList *paths)
   1246 {
   1247 	switch (special) {
   1248 	case SP_SUFFIXES:
   1249 		Suff_ClearSuffixes();
   1250 		break;
   1251 	case SP_PRECIOUS:
   1252 		allPrecious = true;
   1253 		break;
   1254 	case SP_IGNORE:
   1255 		opts.ignoreErrors = true;
   1256 		break;
   1257 	case SP_SILENT:
   1258 		opts.silent = true;
   1259 		break;
   1260 	case SP_PATH:
   1261 		ClearPaths(paths);
   1262 		break;
   1263 #ifdef POSIX
   1264 	case SP_POSIX:
   1265 		if (posix_state == PS_NOW_OR_NEVER) {
   1266 			/*
   1267 			 * With '-r', 'posix.mk' (if it exists)
   1268 			 * can effectively substitute for 'sys.mk',
   1269 			 * otherwise it is an extension.
   1270 			 */
   1271 			Global_Set("%POSIX", "1003.2");
   1272 			IncludeFile("posix.mk", true, false, true);
   1273 		}
   1274 		break;
   1275 #endif
   1276 	default:
   1277 		break;
   1278 	}
   1279 }
   1280 
   1281 static void
   1282 AddToPaths(const char *dir, SearchPathList *paths)
   1283 {
   1284 	if (paths != NULL) {
   1285 		SearchPathListNode *ln;
   1286 		for (ln = paths->first; ln != NULL; ln = ln->next)
   1287 			(void)SearchPath_Add(ln->datum, dir);
   1288 	}
   1289 }
   1290 
   1291 /*
   1292  * If the target was one that doesn't take files as its sources but takes
   1293  * something like suffixes, we take each space-separated word on the line as
   1294  * a something and deal with it accordingly.
   1295  */
   1296 static void
   1297 ParseDependencySourceSpecial(ParseSpecial special, const char *word,
   1298 			     SearchPathList *paths)
   1299 {
   1300 	switch (special) {
   1301 	case SP_SUFFIXES:
   1302 		Suff_AddSuffix(word);
   1303 		break;
   1304 	case SP_PATH:
   1305 		AddToPaths(word, paths);
   1306 		break;
   1307 	case SP_INCLUDES:
   1308 		Suff_AddInclude(word);
   1309 		break;
   1310 	case SP_LIBS:
   1311 		Suff_AddLib(word);
   1312 		break;
   1313 	case SP_NOREADONLY:
   1314 		Var_ReadOnly(word, false);
   1315 		break;
   1316 	case SP_NULL:
   1317 		Suff_SetNull(word);
   1318 		break;
   1319 	case SP_OBJDIR:
   1320 		Main_SetObjdir(false, "%s", word);
   1321 		break;
   1322 	case SP_READONLY:
   1323 		Var_ReadOnly(word, true);
   1324 		break;
   1325 	default:
   1326 		break;
   1327 	}
   1328 }
   1329 
   1330 static bool
   1331 ApplyDependencyTarget(char *name, char *nameEnd, ParseSpecial *inout_special,
   1332 		      GNodeType *inout_targetAttr,
   1333 		      SearchPathList **inout_paths)
   1334 {
   1335 	char savec = *nameEnd;
   1336 	*nameEnd = '\0';
   1337 
   1338 	if (!HandleDependencyTarget(name, inout_special,
   1339 	    inout_targetAttr, inout_paths))
   1340 		return false;
   1341 
   1342 	if (*inout_special == SP_NOT && *name != '\0')
   1343 		HandleDependencyTargetMundane(name);
   1344 	else if (*inout_special == SP_PATH && *name != '.' && *name != '\0')
   1345 		Parse_Error(PARSE_WARNING, "Extra target (%s) ignored", name);
   1346 
   1347 	*nameEnd = savec;
   1348 	return true;
   1349 }
   1350 
   1351 static bool
   1352 ParseDependencyTargets(char **pp,
   1353 		       const char *lstart,
   1354 		       ParseSpecial *inout_special,
   1355 		       GNodeType *inout_targetAttr,
   1356 		       SearchPathList **inout_paths)
   1357 {
   1358 	char *p = *pp;
   1359 
   1360 	for (;;) {
   1361 		char *tgt = p;
   1362 
   1363 		ParseDependencyTargetWord(&p, lstart);
   1364 
   1365 		/*
   1366 		 * If the word is followed by a left parenthesis, it's the
   1367 		 * name of one or more files inside an archive.
   1368 		 */
   1369 		if (!IsEscaped(lstart, p) && *p == '(') {
   1370 			p = tgt;
   1371 			if (!Arch_ParseArchive(&p, targets, SCOPE_CMDLINE)) {
   1372 				Parse_Error(PARSE_FATAL,
   1373 				    "Error in archive specification: \"%s\"",
   1374 				    tgt);
   1375 				return false;
   1376 			}
   1377 			continue;
   1378 		}
   1379 
   1380 		if (*p == '\0') {
   1381 			InvalidLineType(lstart);
   1382 			return false;
   1383 		}
   1384 
   1385 		if (!ApplyDependencyTarget(tgt, p, inout_special,
   1386 		    inout_targetAttr, inout_paths))
   1387 			return false;
   1388 
   1389 		if (*inout_special != SP_NOT && *inout_special != SP_PATH)
   1390 			SkipExtraTargets(&p, lstart);
   1391 		else
   1392 			pp_skip_whitespace(&p);
   1393 
   1394 		if (*p == '\0')
   1395 			break;
   1396 		if ((*p == '!' || *p == ':') && !IsEscaped(lstart, p))
   1397 			break;
   1398 	}
   1399 
   1400 	*pp = p;
   1401 	return true;
   1402 }
   1403 
   1404 static void
   1405 ParseDependencySourcesSpecial(char *start,
   1406 			      ParseSpecial special, SearchPathList *paths)
   1407 {
   1408 	char savec;
   1409 
   1410 	while (*start != '\0') {
   1411 		char *end = start;
   1412 		while (*end != '\0' && !ch_isspace(*end))
   1413 			end++;
   1414 		savec = *end;
   1415 		*end = '\0';
   1416 		ParseDependencySourceSpecial(special, start, paths);
   1417 		*end = savec;
   1418 		if (savec != '\0')
   1419 			end++;
   1420 		pp_skip_whitespace(&end);
   1421 		start = end;
   1422 	}
   1423 }
   1424 
   1425 static void
   1426 LinkVarToTargets(VarAssign *var)
   1427 {
   1428 	GNodeListNode *ln;
   1429 
   1430 	for (ln = targets->first; ln != NULL; ln = ln->next)
   1431 		Parse_Var(var, ln->datum);
   1432 }
   1433 
   1434 static bool
   1435 ParseDependencySourcesMundane(char *start,
   1436 			      ParseSpecial special, GNodeType targetAttr)
   1437 {
   1438 	while (*start != '\0') {
   1439 		char *end = start;
   1440 		VarAssign var;
   1441 
   1442 		/*
   1443 		 * Check for local variable assignment,
   1444 		 * rest of the line is the value.
   1445 		 */
   1446 		if (Parse_IsVar(start, &var)) {
   1447 			/*
   1448 			 * Check if this makefile has disabled
   1449 			 * setting local variables.
   1450 			 */
   1451 			bool target_vars = GetBooleanExpr(
   1452 			    "${.MAKE.TARGET_LOCAL_VARIABLES}", true);
   1453 
   1454 			if (target_vars)
   1455 				LinkVarToTargets(&var);
   1456 			free(var.varname);
   1457 			if (target_vars)
   1458 				return true;
   1459 		}
   1460 
   1461 		/*
   1462 		 * The targets take real sources, so we must beware of archive
   1463 		 * specifications (i.e. things with left parentheses in them)
   1464 		 * and handle them accordingly.
   1465 		 */
   1466 		for (; *end != '\0' && !ch_isspace(*end); end++) {
   1467 			if (*end == '(' && end > start && end[-1] != '$') {
   1468 				/*
   1469 				 * Only stop for a left parenthesis if it
   1470 				 * isn't at the start of a word (that'll be
   1471 				 * for variable changes later) and isn't
   1472 				 * preceded by a dollar sign (a dynamic
   1473 				 * source).
   1474 				 */
   1475 				break;
   1476 			}
   1477 		}
   1478 
   1479 		if (*end == '(') {
   1480 			GNodeList sources = LST_INIT;
   1481 			if (!Arch_ParseArchive(&start, &sources,
   1482 			    SCOPE_CMDLINE)) {
   1483 				Parse_Error(PARSE_FATAL,
   1484 				    "Error in source archive spec \"%s\"",
   1485 				    start);
   1486 				return false;
   1487 			}
   1488 
   1489 			while (!Lst_IsEmpty(&sources)) {
   1490 				GNode *gn = Lst_Dequeue(&sources);
   1491 				ApplyDependencySource(targetAttr, gn->name,
   1492 				    special);
   1493 			}
   1494 			Lst_Done(&sources);
   1495 			end = start;
   1496 		} else {
   1497 			if (*end != '\0') {
   1498 				*end = '\0';
   1499 				end++;
   1500 			}
   1501 
   1502 			ApplyDependencySource(targetAttr, start, special);
   1503 		}
   1504 		pp_skip_whitespace(&end);
   1505 		start = end;
   1506 	}
   1507 	return true;
   1508 }
   1509 
   1510 /*
   1511  * From a dependency line like 'targets: sources', parse the sources.
   1512  *
   1513  * See the tests depsrc-*.mk.
   1514  */
   1515 static void
   1516 ParseDependencySources(char *p, GNodeType targetAttr,
   1517 		       ParseSpecial special, SearchPathList **inout_paths)
   1518 {
   1519 	if (*p == '\0') {
   1520 		HandleDependencySourcesEmpty(special, *inout_paths);
   1521 	} else if (special == SP_MFLAGS) {
   1522 		Main_ParseArgLine(p);
   1523 		return;
   1524 	} else if (special == SP_SHELL) {
   1525 		if (!Job_ParseShell(p)) {
   1526 			Parse_Error(PARSE_FATAL,
   1527 			    "improper shell specification");
   1528 			return;
   1529 		}
   1530 		return;
   1531 	} else if (special == SP_NOTPARALLEL || special == SP_SINGLESHELL ||
   1532 		   special == SP_DELETE_ON_ERROR) {
   1533 		return;
   1534 	}
   1535 
   1536 	/* Now go for the sources. */
   1537 	switch (special) {
   1538 	case SP_INCLUDES:
   1539 	case SP_LIBS:
   1540 	case SP_NOREADONLY:
   1541 	case SP_NULL:
   1542 	case SP_OBJDIR:
   1543 	case SP_PATH:
   1544 	case SP_READONLY:
   1545 	case SP_SUFFIXES:
   1546 		ParseDependencySourcesSpecial(p, special, *inout_paths);
   1547 		if (*inout_paths != NULL) {
   1548 			Lst_Free(*inout_paths);
   1549 			*inout_paths = NULL;
   1550 		}
   1551 		if (special == SP_PATH)
   1552 			Dir_SetPATH();
   1553 		break;
   1554 	default:
   1555 		assert(*inout_paths == NULL);
   1556 		if (!ParseDependencySourcesMundane(p, special, targetAttr))
   1557 			return;
   1558 		break;
   1559 	}
   1560 
   1561 	MaybeUpdateMainTarget();
   1562 }
   1563 
   1564 /*
   1565  * Parse a dependency line consisting of targets, followed by a dependency
   1566  * operator, optionally followed by sources.
   1567  *
   1568  * The nodes of the sources are linked as children to the nodes of the
   1569  * targets. Nodes are created as necessary.
   1570  *
   1571  * The operator is applied to each node in the global 'targets' list,
   1572  * which is where the nodes found for the targets are kept.
   1573  *
   1574  * The sources are parsed in much the same way as the targets, except
   1575  * that they are expanded using the wildcarding scheme of the C-Shell,
   1576  * and a target is created for each expanded word. Each of the resulting
   1577  * nodes is then linked to each of the targets as one of its children.
   1578  *
   1579  * Certain targets and sources such as .PHONY or .PRECIOUS are handled
   1580  * specially, see ParseSpecial.
   1581  *
   1582  * Transformation rules such as '.c.o' are also handled here, see
   1583  * Suff_AddTransform.
   1584  *
   1585  * Upon return, the value of the line is unspecified.
   1586  */
   1587 static void
   1588 ParseDependency(char *line)
   1589 {
   1590 	char *p;
   1591 	SearchPathList *paths;	/* search paths to alter when parsing a list
   1592 				 * of .PATH targets */
   1593 	GNodeType targetAttr;	/* from special sources */
   1594 	ParseSpecial special;	/* in special targets, the children are
   1595 				 * linked as children of the parent but not
   1596 				 * vice versa */
   1597 	GNodeType op;
   1598 
   1599 	DEBUG1(PARSE, "ParseDependency(%s)\n", line);
   1600 	p = line;
   1601 	paths = NULL;
   1602 	targetAttr = OP_NONE;
   1603 	special = SP_NOT;
   1604 
   1605 	if (!ParseDependencyTargets(&p, line, &special, &targetAttr, &paths))
   1606 		goto out;
   1607 
   1608 	if (!Lst_IsEmpty(targets))
   1609 		CheckSpecialMundaneMixture(special);
   1610 
   1611 	op = ParseDependencyOp(&p);
   1612 	if (op == OP_NONE) {
   1613 		InvalidLineType(line);
   1614 		goto out;
   1615 	}
   1616 	ApplyDependencyOperator(op);
   1617 
   1618 	pp_skip_whitespace(&p);
   1619 
   1620 	ParseDependencySources(p, targetAttr, special, &paths);
   1621 
   1622 out:
   1623 	if (paths != NULL)
   1624 		Lst_Free(paths);
   1625 }
   1626 
   1627 /*
   1628  * Determine the assignment operator and adjust the end of the variable
   1629  * name accordingly.
   1630  */
   1631 static VarAssign
   1632 AdjustVarassignOp(const char *name, const char *nameEnd, const char *op,
   1633 		  const char *value)
   1634 {
   1635 	VarAssignOp type;
   1636 	VarAssign va;
   1637 
   1638 	if (op > name && op[-1] == '+') {
   1639 		op--;
   1640 		type = VAR_APPEND;
   1641 
   1642 	} else if (op > name && op[-1] == '?') {
   1643 		op--;
   1644 		type = VAR_DEFAULT;
   1645 
   1646 	} else if (op > name && op[-1] == ':') {
   1647 		op--;
   1648 		type = VAR_SUBST;
   1649 
   1650 	} else if (op > name && op[-1] == '!') {
   1651 		op--;
   1652 		type = VAR_SHELL;
   1653 
   1654 	} else {
   1655 		type = VAR_NORMAL;
   1656 #ifdef SUNSHCMD
   1657 		while (op > name && ch_isspace(op[-1]))
   1658 			op--;
   1659 
   1660 		if (op - name >= 3 && memcmp(op - 3, ":sh", 3) == 0) {
   1661 			op -= 3;
   1662 			type = VAR_SHELL;
   1663 		}
   1664 #endif
   1665 	}
   1666 
   1667 	va.varname = bmake_strsedup(name, nameEnd < op ? nameEnd : op);
   1668 	va.op = type;
   1669 	va.value = value;
   1670 	return va;
   1671 }
   1672 
   1673 /*
   1674  * Parse a variable assignment, consisting of a single-word variable name,
   1675  * optional whitespace, an assignment operator, optional whitespace and the
   1676  * variable value.
   1677  *
   1678  * Note: There is a lexical ambiguity with assignment modifier characters
   1679  * in variable names. This routine interprets the character before the =
   1680  * as a modifier. Therefore, an assignment like
   1681  *	C++=/usr/bin/CC
   1682  * is interpreted as "C+ +=" instead of "C++ =".
   1683  *
   1684  * Used for both lines in a file and command line arguments.
   1685  */
   1686 static bool
   1687 Parse_IsVar(const char *p, VarAssign *out_var)
   1688 {
   1689 	const char *nameStart, *nameEnd, *firstSpace, *eq;
   1690 	int level = 0;
   1691 
   1692 	cpp_skip_hspace(&p);	/* Skip to variable name */
   1693 
   1694 	/*
   1695 	 * During parsing, the '+' of the operator '+=' is initially parsed
   1696 	 * as part of the variable name.  It is later corrected, as is the
   1697 	 * ':sh' modifier. Of these two (nameEnd and eq), the earlier one
   1698 	 * determines the actual end of the variable name.
   1699 	 */
   1700 
   1701 	nameStart = p;
   1702 	firstSpace = NULL;
   1703 
   1704 	/*
   1705 	 * Scan for one of the assignment operators outside a variable
   1706 	 * expansion.
   1707 	 */
   1708 	while (*p != '\0') {
   1709 		char ch = *p++;
   1710 		if (ch == '(' || ch == '{') {
   1711 			level++;
   1712 			continue;
   1713 		}
   1714 		if (ch == ')' || ch == '}') {
   1715 			level--;
   1716 			continue;
   1717 		}
   1718 
   1719 		if (level != 0)
   1720 			continue;
   1721 
   1722 		if ((ch == ' ' || ch == '\t') && firstSpace == NULL)
   1723 			firstSpace = p - 1;
   1724 		while (ch == ' ' || ch == '\t')
   1725 			ch = *p++;
   1726 
   1727 		if (ch == '\0')
   1728 			return false;
   1729 #ifdef SUNSHCMD
   1730 		if (ch == ':' && p[0] == 's' && p[1] == 'h') {
   1731 			p += 2;
   1732 			continue;
   1733 		}
   1734 #endif
   1735 		if (ch == '=')
   1736 			eq = p - 1;
   1737 		else if (*p == '=' &&
   1738 		    (ch == '+' || ch == ':' || ch == '?' || ch == '!'))
   1739 			eq = p;
   1740 		else if (firstSpace != NULL)
   1741 			return false;
   1742 		else
   1743 			continue;
   1744 
   1745 		nameEnd = firstSpace != NULL ? firstSpace : eq;
   1746 		p = eq + 1;
   1747 		cpp_skip_whitespace(&p);
   1748 		*out_var = AdjustVarassignOp(nameStart, nameEnd, eq, p);
   1749 		return true;
   1750 	}
   1751 
   1752 	return false;
   1753 }
   1754 
   1755 /*
   1756  * Check for syntax errors such as unclosed expressions or unknown modifiers.
   1757  */
   1758 static void
   1759 VarCheckSyntax(VarAssignOp type, const char *uvalue, GNode *scope)
   1760 {
   1761 	if (opts.strict) {
   1762 		if (type != VAR_SUBST && strchr(uvalue, '$') != NULL) {
   1763 			char *expandedValue;
   1764 
   1765 			(void)Var_Subst(uvalue, scope, VARE_PARSE_ONLY,
   1766 			    &expandedValue);
   1767 			/* TODO: handle errors */
   1768 			free(expandedValue);
   1769 		}
   1770 	}
   1771 }
   1772 
   1773 /* Perform a variable assignment that uses the operator ':='. */
   1774 static void
   1775 VarAssign_EvalSubst(GNode *scope, const char *name, const char *uvalue,
   1776 		    FStr *out_avalue)
   1777 {
   1778 	char *evalue;
   1779 
   1780 	/*
   1781 	 * make sure that we set the variable the first time to nothing
   1782 	 * so that it gets substituted.
   1783 	 *
   1784 	 * TODO: Add a test that demonstrates why this code is needed,
   1785 	 *  apart from making the debug log longer.
   1786 	 *
   1787 	 * XXX: The variable name is expanded up to 3 times.
   1788 	 */
   1789 	if (!Var_ExistsExpand(scope, name))
   1790 		Var_SetExpand(scope, name, "");
   1791 
   1792 	(void)Var_Subst(uvalue, scope, VARE_KEEP_DOLLAR_UNDEF, &evalue);
   1793 	/* TODO: handle errors */
   1794 
   1795 	Var_SetExpand(scope, name, evalue);
   1796 
   1797 	*out_avalue = FStr_InitOwn(evalue);
   1798 }
   1799 
   1800 /* Perform a variable assignment that uses the operator '!='. */
   1801 static void
   1802 VarAssign_EvalShell(const char *name, const char *uvalue, GNode *scope,
   1803 		    FStr *out_avalue)
   1804 {
   1805 	FStr cmd;
   1806 	char *output, *error;
   1807 
   1808 	cmd = FStr_InitRefer(uvalue);
   1809 	Var_Expand(&cmd, SCOPE_CMDLINE, VARE_UNDEFERR);
   1810 
   1811 	output = Cmd_Exec(cmd.str, &error);
   1812 	Var_SetExpand(scope, name, output);
   1813 	*out_avalue = FStr_InitOwn(output);
   1814 	if (error != NULL) {
   1815 		Parse_Error(PARSE_WARNING, "%s", error);
   1816 		free(error);
   1817 	}
   1818 
   1819 	FStr_Done(&cmd);
   1820 }
   1821 
   1822 /*
   1823  * Perform a variable assignment.
   1824  *
   1825  * The actual value of the variable is returned in *out_true_avalue.
   1826  * Especially for VAR_SUBST and VAR_SHELL this can differ from the literal
   1827  * value.
   1828  *
   1829  * Return whether the assignment was actually performed, which is usually
   1830  * the case.  It is only skipped if the operator is '?=' and the variable
   1831  * already exists.
   1832  */
   1833 static bool
   1834 VarAssign_Eval(const char *name, VarAssignOp op, const char *uvalue,
   1835 	       GNode *scope, FStr *out_true_avalue)
   1836 {
   1837 	FStr avalue = FStr_InitRefer(uvalue);
   1838 
   1839 	if (op == VAR_APPEND)
   1840 		Var_AppendExpand(scope, name, uvalue);
   1841 	else if (op == VAR_SUBST)
   1842 		VarAssign_EvalSubst(scope, name, uvalue, &avalue);
   1843 	else if (op == VAR_SHELL)
   1844 		VarAssign_EvalShell(name, uvalue, scope, &avalue);
   1845 	else {
   1846 		/* XXX: The variable name is expanded up to 2 times. */
   1847 		if (op == VAR_DEFAULT && Var_ExistsExpand(scope, name))
   1848 			return false;
   1849 
   1850 		/* Normal assignment -- just do it. */
   1851 		Var_SetExpand(scope, name, uvalue);
   1852 	}
   1853 
   1854 	*out_true_avalue = avalue;
   1855 	return true;
   1856 }
   1857 
   1858 static void
   1859 VarAssignSpecial(const char *name, const char *avalue)
   1860 {
   1861 	if (strcmp(name, MAKEOVERRIDES) == 0)
   1862 		Main_ExportMAKEFLAGS(false);	/* re-export MAKEFLAGS */
   1863 	else if (strcmp(name, ".CURDIR") == 0) {
   1864 		/*
   1865 		 * Someone is being (too?) clever...
   1866 		 * Let's pretend they know what they are doing and
   1867 		 * re-initialize the 'cur' CachedDir.
   1868 		 */
   1869 		Dir_InitCur(avalue);
   1870 		Dir_SetPATH();
   1871 	} else if (strcmp(name, MAKE_JOB_PREFIX) == 0)
   1872 		Job_SetPrefix();
   1873 	else if (strcmp(name, MAKE_EXPORTED) == 0)
   1874 		Var_ExportVars(avalue);
   1875 }
   1876 
   1877 /* Perform the variable assignment in the given scope. */
   1878 static void
   1879 Parse_Var(VarAssign *var, GNode *scope)
   1880 {
   1881 	FStr avalue;		/* actual value (maybe expanded) */
   1882 
   1883 	VarCheckSyntax(var->op, var->value, scope);
   1884 	if (VarAssign_Eval(var->varname, var->op, var->value, scope, &avalue)) {
   1885 		VarAssignSpecial(var->varname, avalue.str);
   1886 		FStr_Done(&avalue);
   1887 	}
   1888 }
   1889 
   1890 
   1891 /*
   1892  * See if the command possibly calls a sub-make by using the variable
   1893  * expressions ${.MAKE}, ${MAKE} or the plain word "make".
   1894  */
   1895 static bool
   1896 MaybeSubMake(const char *cmd)
   1897 {
   1898 	const char *start;
   1899 
   1900 	for (start = cmd; *start != '\0'; start++) {
   1901 		const char *p = start;
   1902 		char endc;
   1903 
   1904 		/* XXX: What if progname != "make"? */
   1905 		if (strncmp(p, "make", 4) == 0)
   1906 			if (start == cmd || !ch_isalnum(p[-1]))
   1907 				if (!ch_isalnum(p[4]))
   1908 					return true;
   1909 
   1910 		if (*p != '$')
   1911 			continue;
   1912 		p++;
   1913 
   1914 		if (*p == '{')
   1915 			endc = '}';
   1916 		else if (*p == '(')
   1917 			endc = ')';
   1918 		else
   1919 			continue;
   1920 		p++;
   1921 
   1922 		if (*p == '.')	/* Accept either ${.MAKE} or ${MAKE}. */
   1923 			p++;
   1924 
   1925 		if (strncmp(p, "MAKE", 4) == 0 && p[4] == endc)
   1926 			return true;
   1927 	}
   1928 	return false;
   1929 }
   1930 
   1931 /*
   1932  * Append the command to the target node.
   1933  *
   1934  * The node may be marked as a submake node if the command is determined to
   1935  * be that.
   1936  */
   1937 static void
   1938 GNode_AddCommand(GNode *gn, char *cmd)
   1939 {
   1940 	/* Add to last (ie current) cohort for :: targets */
   1941 	if ((gn->type & OP_DOUBLEDEP) && gn->cohorts.last != NULL)
   1942 		gn = gn->cohorts.last->datum;
   1943 
   1944 	/* if target already supplied, ignore commands */
   1945 	if (!(gn->type & OP_HAS_COMMANDS)) {
   1946 		Lst_Append(&gn->commands, cmd);
   1947 		if (MaybeSubMake(cmd))
   1948 			gn->type |= OP_SUBMAKE;
   1949 		RememberLocation(gn);
   1950 	} else {
   1951 #if 0
   1952 		/* XXX: We cannot do this until we fix the tree */
   1953 		Lst_Append(&gn->commands, cmd);
   1954 		Parse_Error(PARSE_WARNING,
   1955 		    "overriding commands for target \"%s\"; "
   1956 		    "previous commands defined at %s: %u ignored",
   1957 		    gn->name, gn->fname, gn->lineno);
   1958 #else
   1959 		Parse_Error(PARSE_WARNING,
   1960 		    "duplicate script for target \"%s\" ignored",
   1961 		    gn->name);
   1962 		ParseErrorInternal(gn, PARSE_WARNING,
   1963 		    "using previous script for \"%s\" defined here",
   1964 		    gn->name);
   1965 #endif
   1966 	}
   1967 }
   1968 
   1969 /*
   1970  * Add a directory to the path searched for included makefiles bracketed
   1971  * by double-quotes.
   1972  */
   1973 void
   1974 Parse_AddIncludeDir(const char *dir)
   1975 {
   1976 	(void)SearchPath_Add(parseIncPath, dir);
   1977 }
   1978 
   1979 
   1980 /*
   1981  * Parse a directive like '.include' or '.-include'.
   1982  *
   1983  * .include "user-makefile.mk"
   1984  * .include <system-makefile.mk>
   1985  */
   1986 static void
   1987 ParseInclude(char *directive)
   1988 {
   1989 	char endc;		/* '>' or '"' */
   1990 	char *p;
   1991 	bool silent = directive[0] != 'i';
   1992 	FStr file;
   1993 
   1994 	p = directive + (silent ? 8 : 7);
   1995 	pp_skip_hspace(&p);
   1996 
   1997 	if (*p != '"' && *p != '<') {
   1998 		Parse_Error(PARSE_FATAL,
   1999 		    ".include filename must be delimited by '\"' or '<'");
   2000 		return;
   2001 	}
   2002 
   2003 	if (*p++ == '<')
   2004 		endc = '>';
   2005 	else
   2006 		endc = '"';
   2007 	file = FStr_InitRefer(p);
   2008 
   2009 	/* Skip to matching delimiter */
   2010 	while (*p != '\0' && *p != endc)
   2011 		p++;
   2012 
   2013 	if (*p != endc) {
   2014 		Parse_Error(PARSE_FATAL,
   2015 		    "Unclosed .include filename. '%c' expected", endc);
   2016 		return;
   2017 	}
   2018 
   2019 	*p = '\0';
   2020 
   2021 	Var_Expand(&file, SCOPE_CMDLINE, VARE_WANTRES);
   2022 	IncludeFile(file.str, endc == '>', directive[0] == 'd', silent);
   2023 	FStr_Done(&file);
   2024 }
   2025 
   2026 /*
   2027  * Split filename into dirname + basename, then assign these to the
   2028  * given variables.
   2029  */
   2030 static void
   2031 SetFilenameVars(const char *filename, const char *dirvar, const char *filevar)
   2032 {
   2033 	const char *slash, *basename;
   2034 	FStr dirname;
   2035 
   2036 	slash = strrchr(filename, '/');
   2037 	if (slash == NULL) {
   2038 		dirname = FStr_InitRefer(curdir);
   2039 		basename = filename;
   2040 	} else {
   2041 		dirname = FStr_InitOwn(bmake_strsedup(filename, slash));
   2042 		basename = slash + 1;
   2043 	}
   2044 
   2045 	Global_Set(dirvar, dirname.str);
   2046 	Global_Set(filevar, basename);
   2047 
   2048 	DEBUG4(PARSE, "SetFilenameVars: ${%s} = `%s' ${%s} = `%s'\n",
   2049 	    dirvar, dirname.str, filevar, basename);
   2050 	FStr_Done(&dirname);
   2051 }
   2052 
   2053 /*
   2054  * Return the immediately including file.
   2055  *
   2056  * This is made complicated since the .for loop is implemented as a special
   2057  * kind of .include; see For_Run.
   2058  */
   2059 static const char *
   2060 GetActuallyIncludingFile(void)
   2061 {
   2062 	size_t i;
   2063 	const IncludedFile *incs = GetInclude(0);
   2064 
   2065 	for (i = includes.len; i >= 2; i--)
   2066 		if (incs[i - 1].forLoop == NULL)
   2067 			return incs[i - 2].name.str;
   2068 	return NULL;
   2069 }
   2070 
   2071 /* Set .PARSEDIR, .PARSEFILE, .INCLUDEDFROMDIR and .INCLUDEDFROMFILE. */
   2072 static void
   2073 SetParseFile(const char *filename)
   2074 {
   2075 	const char *including;
   2076 
   2077 	SetFilenameVars(filename, ".PARSEDIR", ".PARSEFILE");
   2078 
   2079 	including = GetActuallyIncludingFile();
   2080 	if (including != NULL) {
   2081 		SetFilenameVars(including,
   2082 		    ".INCLUDEDFROMDIR", ".INCLUDEDFROMFILE");
   2083 	} else {
   2084 		Global_Delete(".INCLUDEDFROMDIR");
   2085 		Global_Delete(".INCLUDEDFROMFILE");
   2086 	}
   2087 }
   2088 
   2089 static bool
   2090 StrContainsWord(const char *str, const char *word)
   2091 {
   2092 	size_t strLen = strlen(str);
   2093 	size_t wordLen = strlen(word);
   2094 	const char *p;
   2095 
   2096 	if (strLen < wordLen)
   2097 		return false;
   2098 
   2099 	for (p = str; p != NULL; p = strchr(p, ' ')) {
   2100 		if (*p == ' ')
   2101 			p++;
   2102 		if (p > str + strLen - wordLen)
   2103 			return false;
   2104 
   2105 		if (memcmp(p, word, wordLen) == 0 &&
   2106 		    (p[wordLen] == '\0' || p[wordLen] == ' '))
   2107 			return true;
   2108 	}
   2109 	return false;
   2110 }
   2111 
   2112 /*
   2113  * XXX: Searching through a set of words with this linear search is
   2114  * inefficient for variables that contain thousands of words.
   2115  *
   2116  * XXX: The paths in this list don't seem to be normalized in any way.
   2117  */
   2118 static bool
   2119 VarContainsWord(const char *varname, const char *word)
   2120 {
   2121 	FStr val = Var_Value(SCOPE_GLOBAL, varname);
   2122 	bool found = val.str != NULL && StrContainsWord(val.str, word);
   2123 	FStr_Done(&val);
   2124 	return found;
   2125 }
   2126 
   2127 /*
   2128  * Track the makefiles we read - so makefiles can set dependencies on them.
   2129  * Avoid adding anything more than once.
   2130  *
   2131  * Time complexity: O(n) per call, in total O(n^2), where n is the number
   2132  * of makefiles that have been loaded.
   2133  */
   2134 static void
   2135 TrackInput(const char *name)
   2136 {
   2137 	if (!VarContainsWord(MAKE_MAKEFILES, name))
   2138 		Global_Append(MAKE_MAKEFILES, name);
   2139 }
   2140 
   2141 
   2142 /* Parse from the given buffer, later return to the current file. */
   2143 void
   2144 Parse_PushInput(const char *name, unsigned lineno, unsigned readLines,
   2145 		Buffer buf, struct ForLoop *forLoop)
   2146 {
   2147 	IncludedFile *curFile;
   2148 
   2149 	if (forLoop != NULL)
   2150 		name = CurFile()->name.str;
   2151 	else
   2152 		TrackInput(name);
   2153 
   2154 	DEBUG3(PARSE, "Parse_PushInput: %s %s, line %u\n",
   2155 	    forLoop != NULL ? ".for loop in": "file", name, lineno);
   2156 
   2157 	curFile = Vector_Push(&includes);
   2158 	curFile->name = FStr_InitOwn(bmake_strdup(name));
   2159 	curFile->lineno = lineno;
   2160 	curFile->readLines = readLines;
   2161 	curFile->forHeadLineno = lineno;
   2162 	curFile->forBodyReadLines = readLines;
   2163 	curFile->buf = buf;
   2164 	curFile->depending = doing_depend;	/* restore this on EOF */
   2165 	curFile->forLoop = forLoop;
   2166 
   2167 	if (forLoop != NULL && !For_NextIteration(forLoop, &curFile->buf))
   2168 		abort();	/* see For_Run */
   2169 
   2170 	curFile->buf_ptr = curFile->buf.data;
   2171 	curFile->buf_end = curFile->buf.data + curFile->buf.len;
   2172 	curFile->condMinDepth = cond_depth;
   2173 	SetParseFile(name);
   2174 }
   2175 
   2176 /* Check if the directive is an include directive. */
   2177 static bool
   2178 IsInclude(const char *dir, bool sysv)
   2179 {
   2180 	if (dir[0] == 's' || dir[0] == '-' || (dir[0] == 'd' && !sysv))
   2181 		dir++;
   2182 
   2183 	if (strncmp(dir, "include", 7) != 0)
   2184 		return false;
   2185 
   2186 	/* Space is not mandatory for BSD .include */
   2187 	return !sysv || ch_isspace(dir[7]);
   2188 }
   2189 
   2190 
   2191 #ifdef SYSVINCLUDE
   2192 /* Check if the line is a SYSV include directive. */
   2193 static bool
   2194 IsSysVInclude(const char *line)
   2195 {
   2196 	const char *p;
   2197 
   2198 	if (!IsInclude(line, true))
   2199 		return false;
   2200 
   2201 	/* Avoid interpreting a dependency line as an include */
   2202 	for (p = line; (p = strchr(p, ':')) != NULL;) {
   2203 
   2204 		/* end of line -> it's a dependency */
   2205 		if (*++p == '\0')
   2206 			return false;
   2207 
   2208 		/* '::' operator or ': ' -> it's a dependency */
   2209 		if (*p == ':' || ch_isspace(*p))
   2210 			return false;
   2211 	}
   2212 	return true;
   2213 }
   2214 
   2215 /* Push to another file.  The line points to the word "include". */
   2216 static void
   2217 ParseTraditionalInclude(char *line)
   2218 {
   2219 	char *cp;		/* current position in file spec */
   2220 	bool done = false;
   2221 	bool silent = line[0] != 'i';
   2222 	char *file = line + (silent ? 8 : 7);
   2223 	char *all_files;
   2224 
   2225 	DEBUG1(PARSE, "ParseTraditionalInclude: %s\n", file);
   2226 
   2227 	pp_skip_whitespace(&file);
   2228 
   2229 	(void)Var_Subst(file, SCOPE_CMDLINE, VARE_WANTRES, &all_files);
   2230 	/* TODO: handle errors */
   2231 
   2232 	for (file = all_files; !done; file = cp + 1) {
   2233 		/* Skip to end of line or next whitespace */
   2234 		for (cp = file; *cp != '\0' && !ch_isspace(*cp); cp++)
   2235 			continue;
   2236 
   2237 		if (*cp != '\0')
   2238 			*cp = '\0';
   2239 		else
   2240 			done = true;
   2241 
   2242 		IncludeFile(file, false, false, silent);
   2243 	}
   2244 
   2245 	free(all_files);
   2246 }
   2247 #endif
   2248 
   2249 #ifdef GMAKEEXPORT
   2250 /* Parse "export <variable>=<value>", and actually export it. */
   2251 static void
   2252 ParseGmakeExport(char *line)
   2253 {
   2254 	char *variable = line + 6;
   2255 	char *value;
   2256 
   2257 	DEBUG1(PARSE, "ParseGmakeExport: %s\n", variable);
   2258 
   2259 	pp_skip_whitespace(&variable);
   2260 
   2261 	for (value = variable; *value != '\0' && *value != '='; value++)
   2262 		continue;
   2263 
   2264 	if (*value != '=') {
   2265 		Parse_Error(PARSE_FATAL,
   2266 		    "Variable/Value missing from \"export\"");
   2267 		return;
   2268 	}
   2269 	*value++ = '\0';	/* terminate variable */
   2270 
   2271 	/*
   2272 	 * Expand the value before putting it in the environment.
   2273 	 */
   2274 	(void)Var_Subst(value, SCOPE_CMDLINE, VARE_WANTRES, &value);
   2275 	/* TODO: handle errors */
   2276 
   2277 	setenv(variable, value, 1);
   2278 	free(value);
   2279 }
   2280 #endif
   2281 
   2282 /*
   2283  * Called when EOF is reached in the current file. If we were reading an
   2284  * include file or a .for loop, the includes stack is popped and things set
   2285  * up to go back to reading the previous file at the previous location.
   2286  *
   2287  * Results:
   2288  *	true to continue parsing, i.e. it had only reached the end of an
   2289  *	included file, false if the main file has been parsed completely.
   2290  */
   2291 static bool
   2292 ParseEOF(void)
   2293 {
   2294 	IncludedFile *curFile = CurFile();
   2295 
   2296 	doing_depend = curFile->depending;
   2297 	if (curFile->forLoop != NULL &&
   2298 	    For_NextIteration(curFile->forLoop, &curFile->buf)) {
   2299 		curFile->buf_ptr = curFile->buf.data;
   2300 		curFile->buf_end = curFile->buf.data + curFile->buf.len;
   2301 		curFile->readLines = curFile->forBodyReadLines;
   2302 		return true;
   2303 	}
   2304 
   2305 	Cond_EndFile();
   2306 
   2307 	FStr_Done(&curFile->name);
   2308 	Buf_Done(&curFile->buf);
   2309 	if (curFile->forLoop != NULL)
   2310 		ForLoop_Free(curFile->forLoop);
   2311 	Vector_Pop(&includes);
   2312 
   2313 	if (includes.len == 0) {
   2314 		/* We've run out of input */
   2315 		Global_Delete(".PARSEDIR");
   2316 		Global_Delete(".PARSEFILE");
   2317 		Global_Delete(".INCLUDEDFROMDIR");
   2318 		Global_Delete(".INCLUDEDFROMFILE");
   2319 		return false;
   2320 	}
   2321 
   2322 	curFile = CurFile();
   2323 	DEBUG2(PARSE, "ParseEOF: returning to file %s, line %u\n",
   2324 	    curFile->name.str, curFile->readLines + 1);
   2325 
   2326 	SetParseFile(curFile->name.str);
   2327 	return true;
   2328 }
   2329 
   2330 typedef enum ParseRawLineResult {
   2331 	PRLR_LINE,
   2332 	PRLR_EOF,
   2333 	PRLR_ERROR
   2334 } ParseRawLineResult;
   2335 
   2336 /*
   2337  * Parse until the end of a line, taking into account lines that end with
   2338  * backslash-newline.  The resulting line goes from out_line to out_line_end;
   2339  * the line is not null-terminated.
   2340  */
   2341 static ParseRawLineResult
   2342 ParseRawLine(IncludedFile *curFile, char **out_line, char **out_line_end,
   2343 	     char **out_firstBackslash, char **out_commentLineEnd)
   2344 {
   2345 	char *line = curFile->buf_ptr;
   2346 	char *buf_end = curFile->buf_end;
   2347 	char *p = line;
   2348 	char *line_end = line;
   2349 	char *firstBackslash = NULL;
   2350 	char *commentLineEnd = NULL;
   2351 	ParseRawLineResult res = PRLR_LINE;
   2352 
   2353 	curFile->readLines++;
   2354 
   2355 	for (;;) {
   2356 		char ch;
   2357 
   2358 		if (p == buf_end) {
   2359 			res = PRLR_EOF;
   2360 			break;
   2361 		}
   2362 
   2363 		ch = *p;
   2364 		if (ch == '\0' || (ch == '\\' && p[1] == '\0')) {
   2365 			Parse_Error(PARSE_FATAL, "Zero byte read from file");
   2366 			return PRLR_ERROR;
   2367 		}
   2368 
   2369 		/* Treat next character after '\' as literal. */
   2370 		if (ch == '\\') {
   2371 			if (firstBackslash == NULL)
   2372 				firstBackslash = p;
   2373 			if (p[1] == '\n') {
   2374 				curFile->readLines++;
   2375 				if (p + 2 == buf_end) {
   2376 					line_end = p;
   2377 					*line_end = '\n';
   2378 					p += 2;
   2379 					continue;
   2380 				}
   2381 			}
   2382 			p += 2;
   2383 			line_end = p;
   2384 			assert(p <= buf_end);
   2385 			continue;
   2386 		}
   2387 
   2388 		/*
   2389 		 * Remember the first '#' for comment stripping, unless
   2390 		 * the previous char was '[', as in the modifier ':[#]'.
   2391 		 */
   2392 		if (ch == '#' && commentLineEnd == NULL &&
   2393 		    !(p > line && p[-1] == '['))
   2394 			commentLineEnd = line_end;
   2395 
   2396 		p++;
   2397 		if (ch == '\n')
   2398 			break;
   2399 
   2400 		/* We are not interested in trailing whitespace. */
   2401 		if (!ch_isspace(ch))
   2402 			line_end = p;
   2403 	}
   2404 
   2405 	curFile->buf_ptr = p;
   2406 	*out_line = line;
   2407 	*out_line_end = line_end;
   2408 	*out_firstBackslash = firstBackslash;
   2409 	*out_commentLineEnd = commentLineEnd;
   2410 	return res;
   2411 }
   2412 
   2413 /*
   2414  * Beginning at start, unescape '\#' to '#' and replace backslash-newline
   2415  * with a single space.
   2416  */
   2417 static void
   2418 UnescapeBackslash(char *line, char *start)
   2419 {
   2420 	const char *src = start;
   2421 	char *dst = start;
   2422 	char *spaceStart = line;
   2423 
   2424 	for (;;) {
   2425 		char ch = *src++;
   2426 		if (ch != '\\') {
   2427 			if (ch == '\0')
   2428 				break;
   2429 			*dst++ = ch;
   2430 			continue;
   2431 		}
   2432 
   2433 		ch = *src++;
   2434 		if (ch == '\0') {
   2435 			/* Delete '\\' at the end of the buffer. */
   2436 			dst--;
   2437 			break;
   2438 		}
   2439 
   2440 		/* Delete '\\' from before '#' on non-command lines. */
   2441 		if (ch == '#' && line[0] != '\t')
   2442 			*dst++ = ch;
   2443 		else if (ch == '\n') {
   2444 			cpp_skip_hspace(&src);
   2445 			*dst++ = ' ';
   2446 		} else {
   2447 			/* Leave '\\' in the buffer for later. */
   2448 			*dst++ = '\\';
   2449 			*dst++ = ch;
   2450 			/* Keep an escaped ' ' at the line end. */
   2451 			spaceStart = dst;
   2452 		}
   2453 	}
   2454 
   2455 	/* Delete any trailing spaces - eg from empty continuations */
   2456 	while (dst > spaceStart && ch_isspace(dst[-1]))
   2457 		dst--;
   2458 	*dst = '\0';
   2459 }
   2460 
   2461 typedef enum LineKind {
   2462 	/*
   2463 	 * Return the next line that is neither empty nor a comment.
   2464 	 * Backslash line continuations are folded into a single space.
   2465 	 * A trailing comment, if any, is discarded.
   2466 	 */
   2467 	LK_NONEMPTY,
   2468 
   2469 	/*
   2470 	 * Return the next line, even if it is empty or a comment.
   2471 	 * Preserve backslash-newline to keep the line numbers correct.
   2472 	 *
   2473 	 * Used in .for loops to collect the body of the loop while waiting
   2474 	 * for the corresponding .endfor.
   2475 	 */
   2476 	LK_FOR_BODY,
   2477 
   2478 	/*
   2479 	 * Return the next line that starts with a dot.
   2480 	 * Backslash line continuations are folded into a single space.
   2481 	 * A trailing comment, if any, is discarded.
   2482 	 *
   2483 	 * Used in .if directives to skip over irrelevant branches while
   2484 	 * waiting for the corresponding .endif.
   2485 	 */
   2486 	LK_DOT
   2487 } LineKind;
   2488 
   2489 /*
   2490  * Return the next "interesting" logical line from the current file.  The
   2491  * returned string will be freed at the end of including the file.
   2492  */
   2493 static char *
   2494 ReadLowLevelLine(LineKind kind)
   2495 {
   2496 	IncludedFile *curFile = CurFile();
   2497 	ParseRawLineResult res;
   2498 	char *line;
   2499 	char *line_end;
   2500 	char *firstBackslash;
   2501 	char *commentLineEnd;
   2502 
   2503 	for (;;) {
   2504 		curFile->lineno = curFile->readLines + 1;
   2505 		res = ParseRawLine(curFile,
   2506 		    &line, &line_end, &firstBackslash, &commentLineEnd);
   2507 		if (res == PRLR_ERROR)
   2508 			return NULL;
   2509 
   2510 		if (line == line_end || line == commentLineEnd) {
   2511 			if (res == PRLR_EOF)
   2512 				return NULL;
   2513 			if (kind != LK_FOR_BODY)
   2514 				continue;
   2515 		}
   2516 
   2517 		/* We now have a line of data */
   2518 		assert(ch_isspace(*line_end));
   2519 		*line_end = '\0';
   2520 
   2521 		if (kind == LK_FOR_BODY)
   2522 			return line;	/* Don't join the physical lines. */
   2523 
   2524 		if (kind == LK_DOT && line[0] != '.')
   2525 			continue;
   2526 		break;
   2527 	}
   2528 
   2529 	if (commentLineEnd != NULL && line[0] != '\t')
   2530 		*commentLineEnd = '\0';
   2531 	if (firstBackslash != NULL)
   2532 		UnescapeBackslash(line, firstBackslash);
   2533 	return line;
   2534 }
   2535 
   2536 static bool
   2537 SkipIrrelevantBranches(void)
   2538 {
   2539 	const char *line;
   2540 
   2541 	while ((line = ReadLowLevelLine(LK_DOT)) != NULL) {
   2542 		if (Cond_EvalLine(line) == CR_TRUE)
   2543 			return true;
   2544 		/*
   2545 		 * TODO: Check for typos in .elif directives such as .elsif
   2546 		 * or .elseif.
   2547 		 *
   2548 		 * This check will probably duplicate some of the code in
   2549 		 * ParseLine.  Most of the code there cannot apply, only
   2550 		 * ParseVarassign and ParseDependencyLine can, and to prevent
   2551 		 * code duplication, these would need to be called with a
   2552 		 * flag called onlyCheckSyntax.
   2553 		 *
   2554 		 * See directive-elif.mk for details.
   2555 		 */
   2556 	}
   2557 
   2558 	return false;
   2559 }
   2560 
   2561 static bool
   2562 ParseForLoop(const char *line)
   2563 {
   2564 	int rval;
   2565 	unsigned forHeadLineno;
   2566 	unsigned bodyReadLines;
   2567 	int forLevel;
   2568 
   2569 	rval = For_Eval(line);
   2570 	if (rval == 0)
   2571 		return false;	/* Not a .for line */
   2572 	if (rval < 0)
   2573 		return true;	/* Syntax error - error printed, ignore line */
   2574 
   2575 	forHeadLineno = CurFile()->lineno;
   2576 	bodyReadLines = CurFile()->readLines;
   2577 
   2578 	/* Accumulate the loop body until the matching '.endfor'. */
   2579 	forLevel = 1;
   2580 	do {
   2581 		line = ReadLowLevelLine(LK_FOR_BODY);
   2582 		if (line == NULL) {
   2583 			Parse_Error(PARSE_FATAL,
   2584 			    "Unexpected end of file in .for loop");
   2585 			break;
   2586 		}
   2587 	} while (For_Accum(line, &forLevel));
   2588 
   2589 	For_Run(forHeadLineno, bodyReadLines);
   2590 	return true;
   2591 }
   2592 
   2593 /*
   2594  * Read an entire line from the input file.
   2595  *
   2596  * Empty lines, .if and .for are completely handled by this function,
   2597  * leaving only variable assignments, other directives, dependency lines
   2598  * and shell commands to the caller.
   2599  *
   2600  * Return a line without trailing whitespace, or NULL for EOF.  The returned
   2601  * string will be freed at the end of including the file.
   2602  */
   2603 static char *
   2604 ReadHighLevelLine(void)
   2605 {
   2606 	char *line;
   2607 
   2608 	for (;;) {
   2609 		line = ReadLowLevelLine(LK_NONEMPTY);
   2610 		if (posix_state == PS_MAYBE_NEXT_LINE)
   2611 			posix_state = PS_NOW_OR_NEVER;
   2612 		else
   2613 			posix_state = PS_TOO_LATE;
   2614 		if (line == NULL)
   2615 			return NULL;
   2616 
   2617 		if (line[0] != '.')
   2618 			return line;
   2619 
   2620 		switch (Cond_EvalLine(line)) {
   2621 		case CR_FALSE:	/* May also mean a syntax error. */
   2622 			if (!SkipIrrelevantBranches())
   2623 				return NULL;
   2624 			continue;
   2625 		case CR_TRUE:
   2626 			continue;
   2627 		case CR_ERROR:	/* Not a conditional line */
   2628 			if (ParseForLoop(line))
   2629 				continue;
   2630 			break;
   2631 		}
   2632 		return line;
   2633 	}
   2634 }
   2635 
   2636 static void
   2637 FinishDependencyGroup(void)
   2638 {
   2639 	GNodeListNode *ln;
   2640 
   2641 	if (targets == NULL)
   2642 		return;
   2643 
   2644 	for (ln = targets->first; ln != NULL; ln = ln->next) {
   2645 		GNode *gn = ln->datum;
   2646 
   2647 		Suff_EndTransform(gn);
   2648 
   2649 		/*
   2650 		 * Mark the target as already having commands if it does, to
   2651 		 * keep from having shell commands on multiple dependency
   2652 		 * lines.
   2653 		 */
   2654 		if (!Lst_IsEmpty(&gn->commands))
   2655 			gn->type |= OP_HAS_COMMANDS;
   2656 	}
   2657 
   2658 	Lst_Free(targets);
   2659 	targets = NULL;
   2660 }
   2661 
   2662 /* Add the command to each target from the current dependency spec. */
   2663 static void
   2664 ParseLine_ShellCommand(const char *p)
   2665 {
   2666 	cpp_skip_whitespace(&p);
   2667 	if (*p == '\0')
   2668 		return;		/* skip empty commands */
   2669 
   2670 	if (targets == NULL) {
   2671 		Parse_Error(PARSE_FATAL,
   2672 		    "Unassociated shell command \"%s\"", p);
   2673 		return;
   2674 	}
   2675 
   2676 	{
   2677 		char *cmd = bmake_strdup(p);
   2678 		GNodeListNode *ln;
   2679 
   2680 		for (ln = targets->first; ln != NULL; ln = ln->next) {
   2681 			GNode *gn = ln->datum;
   2682 			GNode_AddCommand(gn, cmd);
   2683 		}
   2684 #ifdef CLEANUP
   2685 		Lst_Append(&targCmds, cmd);
   2686 #endif
   2687 	}
   2688 }
   2689 
   2690 static void
   2691 HandleBreak(void)
   2692 {
   2693 	IncludedFile *curFile = CurFile();
   2694 
   2695 	if (curFile->forLoop != NULL) {
   2696 		/* pretend we reached EOF */
   2697 		For_Break(curFile->forLoop);
   2698 		cond_depth = CurFile_CondMinDepth();
   2699 		ParseEOF();
   2700 	} else
   2701 		Parse_Error(PARSE_FATAL, "break outside of for loop");
   2702 }
   2703 
   2704 /*
   2705  * See if the line starts with one of the known directives, and if so, handle
   2706  * the directive.
   2707  */
   2708 static bool
   2709 ParseDirective(char *line)
   2710 {
   2711 	char *cp = line + 1;
   2712 	const char *arg;
   2713 	Substring dir;
   2714 
   2715 	pp_skip_whitespace(&cp);
   2716 	if (IsInclude(cp, false)) {
   2717 		ParseInclude(cp);
   2718 		return true;
   2719 	}
   2720 
   2721 	dir.start = cp;
   2722 	while (ch_islower(*cp) || *cp == '-')
   2723 		cp++;
   2724 	dir.end = cp;
   2725 
   2726 	if (*cp != '\0' && !ch_isspace(*cp))
   2727 		return false;
   2728 
   2729 	pp_skip_whitespace(&cp);
   2730 	arg = cp;
   2731 
   2732 	if (Substring_Equals(dir, "break"))
   2733 		HandleBreak();
   2734 	else if (Substring_Equals(dir, "undef"))
   2735 		Var_Undef(arg);
   2736 	else if (Substring_Equals(dir, "export"))
   2737 		Var_Export(VEM_PLAIN, arg);
   2738 	else if (Substring_Equals(dir, "export-env"))
   2739 		Var_Export(VEM_ENV, arg);
   2740 	else if (Substring_Equals(dir, "export-literal"))
   2741 		Var_Export(VEM_LITERAL, arg);
   2742 	else if (Substring_Equals(dir, "unexport"))
   2743 		Var_UnExport(false, arg);
   2744 	else if (Substring_Equals(dir, "unexport-env"))
   2745 		Var_UnExport(true, arg);
   2746 	else if (Substring_Equals(dir, "info"))
   2747 		HandleMessage(PARSE_INFO, "info", arg);
   2748 	else if (Substring_Equals(dir, "warning"))
   2749 		HandleMessage(PARSE_WARNING, "warning", arg);
   2750 	else if (Substring_Equals(dir, "error"))
   2751 		HandleMessage(PARSE_FATAL, "error", arg);
   2752 	else
   2753 		return false;
   2754 	return true;
   2755 }
   2756 
   2757 bool
   2758 Parse_VarAssign(const char *line, bool finishDependencyGroup, GNode *scope)
   2759 {
   2760 	VarAssign var;
   2761 
   2762 	if (!Parse_IsVar(line, &var))
   2763 		return false;
   2764 	if (finishDependencyGroup)
   2765 		FinishDependencyGroup();
   2766 	Parse_Var(&var, scope);
   2767 	free(var.varname);
   2768 	return true;
   2769 }
   2770 
   2771 static char *
   2772 FindSemicolon(char *p)
   2773 {
   2774 	int level = 0;
   2775 
   2776 	for (; *p != '\0'; p++) {
   2777 		if (*p == '\\' && p[1] != '\0') {
   2778 			p++;
   2779 			continue;
   2780 		}
   2781 
   2782 		if (*p == '$' && (p[1] == '(' || p[1] == '{'))
   2783 			level++;
   2784 		else if (level > 0 && (*p == ')' || *p == '}'))
   2785 			level--;
   2786 		else if (level == 0 && *p == ';')
   2787 			break;
   2788 	}
   2789 	return p;
   2790 }
   2791 
   2792 /*
   2793  * dependency	-> [target...] op [source...] [';' command]
   2794  * op		-> ':' | '::' | '!'
   2795  */
   2796 static void
   2797 ParseDependencyLine(char *line)
   2798 {
   2799 	VarEvalMode emode;
   2800 	char *expanded_line;
   2801 	const char *shellcmd = NULL;
   2802 
   2803 	/*
   2804 	 * For some reason - probably to make the parser impossible -
   2805 	 * a ';' can be used to separate commands from dependencies.
   2806 	 * Attempt to skip over ';' inside substitution patterns.
   2807 	 */
   2808 	{
   2809 		char *semicolon = FindSemicolon(line);
   2810 		if (*semicolon != '\0') {
   2811 			/* Terminate the dependency list at the ';' */
   2812 			*semicolon = '\0';
   2813 			shellcmd = semicolon + 1;
   2814 		}
   2815 	}
   2816 
   2817 	/*
   2818 	 * We now know it's a dependency line so it needs to have all
   2819 	 * variables expanded before being parsed.
   2820 	 *
   2821 	 * XXX: Ideally the dependency line would first be split into
   2822 	 * its left-hand side, dependency operator and right-hand side,
   2823 	 * and then each side would be expanded on its own.  This would
   2824 	 * allow for the left-hand side to allow only defined variables
   2825 	 * and to allow variables on the right-hand side to be undefined
   2826 	 * as well.
   2827 	 *
   2828 	 * Parsing the line first would also prevent that targets
   2829 	 * generated from variable expressions are interpreted as the
   2830 	 * dependency operator, such as in "target${:U\:} middle: source",
   2831 	 * in which the middle is interpreted as a source, not a target.
   2832 	 */
   2833 
   2834 	/*
   2835 	 * In lint mode, allow undefined variables to appear in dependency
   2836 	 * lines.
   2837 	 *
   2838 	 * Ideally, only the right-hand side would allow undefined variables
   2839 	 * since it is common to have optional dependencies. Having undefined
   2840 	 * variables on the left-hand side is more unusual though.  Since
   2841 	 * both sides are expanded in a single pass, there is not much choice
   2842 	 * what to do here.
   2843 	 *
   2844 	 * In normal mode, it does not matter whether undefined variables are
   2845 	 * allowed or not since as of 2020-09-14, Var_Parse does not print
   2846 	 * any parse errors in such a case. It simply returns the special
   2847 	 * empty string var_Error, which cannot be detected in the result of
   2848 	 * Var_Subst.
   2849 	 */
   2850 	emode = opts.strict ? VARE_WANTRES : VARE_UNDEFERR;
   2851 	(void)Var_Subst(line, SCOPE_CMDLINE, emode, &expanded_line);
   2852 	/* TODO: handle errors */
   2853 
   2854 	/* Need a fresh list for the target nodes */
   2855 	if (targets != NULL)
   2856 		Lst_Free(targets);
   2857 	targets = Lst_New();
   2858 
   2859 	ParseDependency(expanded_line);
   2860 	free(expanded_line);
   2861 
   2862 	if (shellcmd != NULL)
   2863 		ParseLine_ShellCommand(shellcmd);
   2864 }
   2865 
   2866 static void
   2867 ParseLine(char *line)
   2868 {
   2869 	/*
   2870 	 * Lines that begin with '.' can be pretty much anything:
   2871 	 *	- directives like '.include' or '.if',
   2872 	 *	- suffix rules like '.c.o:',
   2873 	 *	- dependencies for filenames that start with '.',
   2874 	 *	- variable assignments like '.tmp=value'.
   2875 	 */
   2876 	if (line[0] == '.' && ParseDirective(line))
   2877 		return;
   2878 
   2879 	if (line[0] == '\t') {
   2880 		ParseLine_ShellCommand(line + 1);
   2881 		return;
   2882 	}
   2883 
   2884 #ifdef SYSVINCLUDE
   2885 	if (IsSysVInclude(line)) {
   2886 		/*
   2887 		 * It's an S3/S5-style "include".
   2888 		 */
   2889 		ParseTraditionalInclude(line);
   2890 		return;
   2891 	}
   2892 #endif
   2893 
   2894 #ifdef GMAKEEXPORT
   2895 	if (strncmp(line, "export", 6) == 0 && ch_isspace(line[6]) &&
   2896 	    strchr(line, ':') == NULL) {
   2897 		/*
   2898 		 * It's a Gmake "export".
   2899 		 */
   2900 		ParseGmakeExport(line);
   2901 		return;
   2902 	}
   2903 #endif
   2904 
   2905 	if (Parse_VarAssign(line, true, SCOPE_GLOBAL))
   2906 		return;
   2907 
   2908 	FinishDependencyGroup();
   2909 
   2910 	ParseDependencyLine(line);
   2911 }
   2912 
   2913 /*
   2914  * Parse a top-level makefile, incorporating its content into the global
   2915  * dependency graph.
   2916  */
   2917 void
   2918 Parse_File(const char *name, int fd)
   2919 {
   2920 	char *line;
   2921 	Buffer buf;
   2922 
   2923 	buf = LoadFile(name, fd != -1 ? fd : STDIN_FILENO);
   2924 	if (fd != -1)
   2925 		(void)close(fd);
   2926 
   2927 	assert(targets == NULL);
   2928 
   2929 	Parse_PushInput(name, 1, 0, buf, NULL);
   2930 
   2931 	do {
   2932 		while ((line = ReadHighLevelLine()) != NULL) {
   2933 			DEBUG2(PARSE, "Parsing line %u: %s\n",
   2934 			    CurFile()->lineno, line);
   2935 			ParseLine(line);
   2936 		}
   2937 		/* Reached EOF, but it may be just EOF of an include file. */
   2938 	} while (ParseEOF());
   2939 
   2940 	FinishDependencyGroup();
   2941 
   2942 	if (parseErrors != 0) {
   2943 		(void)fflush(stdout);
   2944 		(void)fprintf(stderr,
   2945 		    "%s: Fatal errors encountered -- cannot continue\n",
   2946 		    progname);
   2947 		PrintOnError(NULL, "");
   2948 		exit(1);
   2949 	}
   2950 }
   2951 
   2952 /* Initialize the parsing module. */
   2953 void
   2954 Parse_Init(void)
   2955 {
   2956 	mainNode = NULL;
   2957 	parseIncPath = SearchPath_New();
   2958 	sysIncPath = SearchPath_New();
   2959 	defSysIncPath = SearchPath_New();
   2960 	Vector_Init(&includes, sizeof(IncludedFile));
   2961 }
   2962 
   2963 /* Clean up the parsing module. */
   2964 void
   2965 Parse_End(void)
   2966 {
   2967 #ifdef CLEANUP
   2968 	Lst_DoneCall(&targCmds, free);
   2969 	assert(targets == NULL);
   2970 	SearchPath_Free(defSysIncPath);
   2971 	SearchPath_Free(sysIncPath);
   2972 	SearchPath_Free(parseIncPath);
   2973 	assert(includes.len == 0);
   2974 	Vector_Done(&includes);
   2975 #endif
   2976 }
   2977 
   2978 
   2979 /*
   2980  * Return a list containing the single main target to create.
   2981  * If no such target exists, we Punt with an obnoxious error message.
   2982  */
   2983 void
   2984 Parse_MainName(GNodeList *mainList)
   2985 {
   2986 	if (mainNode == NULL)
   2987 		Punt("no target to make.");
   2988 
   2989 	Lst_Append(mainList, mainNode);
   2990 	if (mainNode->type & OP_DOUBLEDEP)
   2991 		Lst_AppendAll(mainList, &mainNode->cohorts);
   2992 
   2993 	Global_Append(".TARGETS", mainNode->name);
   2994 }
   2995 
   2996 int
   2997 Parse_NumErrors(void)
   2998 {
   2999 	return parseErrors;
   3000 }
   3001