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