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