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