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