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