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