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