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