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