Home | History | Annotate | Line # | Download | only in make
parse.c revision 1.383
      1 /*	$NetBSD: parse.c,v 1.383 2020/10/17 21:32:30 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.383 2020/10/17 21:32:30 rillig Exp $");
    135 
    136 /* types and constants */
    137 
    138 /*
    139  * Structure for a file being read ("included file")
    140  */
    141 typedef struct IFile {
    142     char *fname;		/* name of file */
    143     Boolean fromForLoop;	/* simulated .include by the .for loop */
    144     int lineno;			/* current line number in file */
    145     int first_lineno;		/* line number of start of text */
    146     unsigned int cond_depth;	/* 'if' nesting when file opened */
    147     Boolean depending;		/* state of doing_depend on EOF */
    148     char *P_str;		/* point to base of string buffer */
    149     char *P_ptr;		/* point to next char of string buffer */
    150     char *P_end;		/* point to the end of string buffer */
    151     char *(*nextbuf)(void *, size_t *); /* Function to get more data */
    152     void *nextbuf_arg;		/* Opaque arg for nextbuf() */
    153     struct loadedfile *lf;	/* loadedfile object, if any */
    154 } IFile;
    155 
    156 /*
    157  * Tokens for target attributes
    158  */
    159 typedef enum {
    160     Begin,		/* .BEGIN */
    161     Default,		/* .DEFAULT */
    162     DeleteOnError,	/* .DELETE_ON_ERROR */
    163     End,		/* .END */
    164     dotError,		/* .ERROR */
    165     Ignore,		/* .IGNORE */
    166     Includes,		/* .INCLUDES */
    167     Interrupt,		/* .INTERRUPT */
    168     Libs,		/* .LIBS */
    169     Meta,		/* .META */
    170     MFlags,		/* .MFLAGS or .MAKEFLAGS */
    171     Main,		/* .MAIN and we don't have anything user-specified to
    172 			 * make */
    173     NoExport,		/* .NOEXPORT */
    174     NoMeta,		/* .NOMETA */
    175     NoMetaCmp,		/* .NOMETA_CMP */
    176     NoPath,		/* .NOPATH */
    177     Not,		/* Not special */
    178     NotParallel,	/* .NOTPARALLEL */
    179     Null,		/* .NULL */
    180     ExObjdir,		/* .OBJDIR */
    181     Order,		/* .ORDER */
    182     Parallel,		/* .PARALLEL */
    183     ExPath,		/* .PATH */
    184     Phony,		/* .PHONY */
    185 #ifdef POSIX
    186     Posix,		/* .POSIX */
    187 #endif
    188     Precious,		/* .PRECIOUS */
    189     ExShell,		/* .SHELL */
    190     Silent,		/* .SILENT */
    191     SingleShell,	/* .SINGLESHELL */
    192     Stale,		/* .STALE */
    193     Suffixes,		/* .SUFFIXES */
    194     Wait,		/* .WAIT */
    195     Attribute		/* Generic attribute */
    196 } ParseSpecial;
    197 
    198 typedef List SearchPathList;
    199 
    200 /* result data */
    201 
    202 /*
    203  * The main target to create. This is the first target on the first
    204  * dependency line in the first makefile.
    205  */
    206 static GNode *mainNode;
    207 
    208 /* eval state */
    209 
    210 /* During parsing, the targets from the currently active dependency line,
    211  * or NULL if the current line does not belong to a dependency line, for
    212  * example because it is a variable assignment.
    213  *
    214  * See unit-tests/deptgt.mk, keyword "parse.c:targets". */
    215 static GNodeList *targets;
    216 
    217 #ifdef CLEANUP
    218 /* All shell commands for all targets, in no particular order and possibly
    219  * with duplicates.  Kept in a separate list since the commands from .USE or
    220  * .USEBEFORE nodes are shared with other GNodes, thereby giving up the
    221  * easily understandable ownership over the allocated strings. */
    222 static StringList *targCmds;
    223 #endif
    224 
    225 /*
    226  * Predecessor node for handling .ORDER. Initialized to NULL when .ORDER
    227  * seen, then set to each successive source on the line.
    228  */
    229 static GNode *predecessor;
    230 
    231 /* parser state */
    232 
    233 /* number of fatal errors */
    234 static int fatals = 0;
    235 
    236 /*
    237  * Variables for doing includes
    238  */
    239 
    240 /* current file being read */
    241 static IFile *curFile;
    242 
    243 /* The include chain of makefiles that leads to curFile.  At the bottom of
    244  * the stack is the top-level makefile from the command line, and on top of
    245  * this file, there are the included files or .for loops, up to but excluding
    246  * curFile.
    247  *
    248  * This data could be used to print stack traces on parse errors.  As of
    249  * 2020-09-14, this is not done though.  It seems quite simple to print the
    250  * tuples (fname:lineno:fromForLoop), from top to bottom.  This simple idea is
    251  * made complicated by the fact that the .for loops also use this stack for
    252  * storing information.
    253  *
    254  * The lineno fields of the IFiles with fromForLoop == TRUE look confusing,
    255  * which is demonstrated by the test 'include-main.mk'.  They seem sorted
    256  * backwards since they tell the number of completely parsed lines, which for
    257  * a .for loop is right after the terminating .endfor.  To compensate for this
    258  * confusion, there is another field first_lineno pointing at the start of the
    259  * .for loop, 1-based for human consumption.
    260  *
    261  * To make the stack trace intuitive, the entry below the first .for loop must
    262  * be ignored completely since neither its lineno nor its first_lineno is
    263  * useful.  Instead, the topmost .for loop needs to be printed twice, once
    264  * with its first_lineno and once with its lineno.
    265  *
    266  * As of 2020-09-15, using the above rules, the stack trace for the .info line
    267  * in include-subsub.mk would be:
    268  *
    269  *	curFile:	include-subsub.mk:4
    270  *			(lineno, from an .include)
    271  *	includes[4]:	include-sub.mk:32
    272  *			(lineno, from a .for loop below an .include)
    273  *	includes[4]:	include-sub.mk:31
    274  *			(first_lineno, from a .for loop, lineno == 32)
    275  *	includes[3]:	include-sub.mk:30
    276  *			(first_lineno, from a .for loop, lineno == 33)
    277  *	includes[2]:	include-sub.mk:29
    278  *			(first_lineno, from a .for loop, lineno == 34)
    279  *	includes[1]:	include-sub.mk:35
    280  *			(not printed since it is below a .for loop)
    281  *	includes[0]:	include-main.mk:27
    282  */
    283 static Stack /* of *IFile */ includes;
    284 
    285 /* include paths (lists of directories) */
    286 SearchPath *parseIncPath;	/* dirs for "..." includes */
    287 SearchPath *sysIncPath;		/* dirs for <...> includes */
    288 SearchPath *defIncPath;		/* default for sysIncPath */
    289 
    290 /* parser tables */
    291 
    292 /*
    293  * The parseKeywords table is searched using binary search when deciding
    294  * if a target or source is special. The 'spec' field is the ParseSpecial
    295  * type of the keyword ("Not" if the keyword isn't special as a target) while
    296  * the 'op' field is the operator to apply to the list of targets if the
    297  * keyword is used as a source ("0" if the keyword isn't special as a source)
    298  */
    299 static const struct {
    300     const char   *name;		/* Name of keyword */
    301     ParseSpecial  spec;		/* Type when used as a target */
    302     GNodeType	  op;		/* Operator when used as a source */
    303 } parseKeywords[] = {
    304     { ".BEGIN",		Begin,		0 },
    305     { ".DEFAULT",	Default,	0 },
    306     { ".DELETE_ON_ERROR", DeleteOnError, 0 },
    307     { ".END",		End,		0 },
    308     { ".ERROR",		dotError,	0 },
    309     { ".EXEC",		Attribute,	OP_EXEC },
    310     { ".IGNORE",	Ignore,		OP_IGNORE },
    311     { ".INCLUDES",	Includes,	0 },
    312     { ".INTERRUPT",	Interrupt,	0 },
    313     { ".INVISIBLE",	Attribute,	OP_INVISIBLE },
    314     { ".JOIN",		Attribute,	OP_JOIN },
    315     { ".LIBS",		Libs,		0 },
    316     { ".MADE",		Attribute,	OP_MADE },
    317     { ".MAIN",		Main,		0 },
    318     { ".MAKE",		Attribute,	OP_MAKE },
    319     { ".MAKEFLAGS",	MFlags,		0 },
    320     { ".META",		Meta,		OP_META },
    321     { ".MFLAGS",	MFlags,		0 },
    322     { ".NOMETA",	NoMeta,		OP_NOMETA },
    323     { ".NOMETA_CMP",	NoMetaCmp,	OP_NOMETA_CMP },
    324     { ".NOPATH",	NoPath,		OP_NOPATH },
    325     { ".NOTMAIN",	Attribute,	OP_NOTMAIN },
    326     { ".NOTPARALLEL",	NotParallel,	0 },
    327     { ".NO_PARALLEL",	NotParallel,	0 },
    328     { ".NULL",		Null,		0 },
    329     { ".OBJDIR",	ExObjdir,	0 },
    330     { ".OPTIONAL",	Attribute,	OP_OPTIONAL },
    331     { ".ORDER",		Order,		0 },
    332     { ".PARALLEL",	Parallel,	0 },
    333     { ".PATH",		ExPath,		0 },
    334     { ".PHONY",		Phony,		OP_PHONY },
    335 #ifdef POSIX
    336     { ".POSIX",		Posix,		0 },
    337 #endif
    338     { ".PRECIOUS",	Precious,	OP_PRECIOUS },
    339     { ".RECURSIVE",	Attribute,	OP_MAKE },
    340     { ".SHELL",		ExShell,	0 },
    341     { ".SILENT",	Silent,		OP_SILENT },
    342     { ".SINGLESHELL",	SingleShell,	0 },
    343     { ".STALE",		Stale,		0 },
    344     { ".SUFFIXES",	Suffixes,	0 },
    345     { ".USE",		Attribute,	OP_USE },
    346     { ".USEBEFORE",	Attribute,	OP_USEBEFORE },
    347     { ".WAIT",		Wait,		0 },
    348 };
    349 
    350 /* file loader */
    351 
    352 struct loadedfile {
    353 	const char *path;		/* name, for error reports */
    354 	char *buf;			/* contents buffer */
    355 	size_t len;			/* length of contents */
    356 	size_t maplen;			/* length of mmap area, or 0 */
    357 	Boolean used;			/* XXX: have we used the data yet */
    358 };
    359 
    360 static struct loadedfile *
    361 loadedfile_create(const char *path)
    362 {
    363 	struct loadedfile *lf;
    364 
    365 	lf = bmake_malloc(sizeof(*lf));
    366 	lf->path = path == NULL ? "(stdin)" : path;
    367 	lf->buf = NULL;
    368 	lf->len = 0;
    369 	lf->maplen = 0;
    370 	lf->used = FALSE;
    371 	return lf;
    372 }
    373 
    374 static void
    375 loadedfile_destroy(struct loadedfile *lf)
    376 {
    377 	if (lf->buf != NULL) {
    378 		if (lf->maplen > 0) {
    379 			munmap(lf->buf, lf->maplen);
    380 		} else {
    381 			free(lf->buf);
    382 		}
    383 	}
    384 	free(lf);
    385 }
    386 
    387 /*
    388  * nextbuf() operation for loadedfile, as needed by the weird and twisted
    389  * logic below. Once that's cleaned up, we can get rid of lf->used...
    390  */
    391 static char *
    392 loadedfile_nextbuf(void *x, size_t *len)
    393 {
    394 	struct loadedfile *lf = x;
    395 
    396 	if (lf->used) {
    397 		return NULL;
    398 	}
    399 	lf->used = TRUE;
    400 	*len = lf->len;
    401 	return lf->buf;
    402 }
    403 
    404 /*
    405  * Try to get the size of a file.
    406  */
    407 static Boolean
    408 load_getsize(int fd, size_t *ret)
    409 {
    410 	struct stat st;
    411 
    412 	if (fstat(fd, &st) < 0) {
    413 		return FALSE;
    414 	}
    415 
    416 	if (!S_ISREG(st.st_mode)) {
    417 		return FALSE;
    418 	}
    419 
    420 	/*
    421 	 * st_size is an off_t, which is 64 bits signed; *ret is
    422 	 * size_t, which might be 32 bits unsigned or 64 bits
    423 	 * unsigned. Rather than being elaborate, just punt on
    424 	 * files that are more than 2^31 bytes. We should never
    425 	 * see a makefile that size in practice...
    426 	 *
    427 	 * While we're at it reject negative sizes too, just in case.
    428 	 */
    429 	if (st.st_size < 0 || st.st_size > 0x7fffffff) {
    430 		return FALSE;
    431 	}
    432 
    433 	*ret = (size_t) st.st_size;
    434 	return TRUE;
    435 }
    436 
    437 /*
    438  * Read in a file.
    439  *
    440  * Until the path search logic can be moved under here instead of
    441  * being in the caller in another source file, we need to have the fd
    442  * passed in already open. Bleh.
    443  *
    444  * If the path is NULL use stdin and (to insure against fd leaks)
    445  * assert that the caller passed in -1.
    446  */
    447 static struct loadedfile *
    448 loadfile(const char *path, int fd)
    449 {
    450 	struct loadedfile *lf;
    451 	static unsigned long pagesize = 0;
    452 	ssize_t result;
    453 	size_t bufpos;
    454 
    455 	lf = loadedfile_create(path);
    456 
    457 	if (path == NULL) {
    458 		assert(fd == -1);
    459 		fd = STDIN_FILENO;
    460 	} else {
    461 #if 0 /* notyet */
    462 		fd = open(path, O_RDONLY);
    463 		if (fd < 0) {
    464 			...
    465 			Error("%s: %s", path, strerror(errno));
    466 			exit(1);
    467 		}
    468 #endif
    469 	}
    470 
    471 	if (load_getsize(fd, &lf->len)) {
    472 		/* found a size, try mmap */
    473 		if (pagesize == 0)
    474 			pagesize = (unsigned long)sysconf(_SC_PAGESIZE);
    475 		if (pagesize == 0 || pagesize == (unsigned long)-1) {
    476 			pagesize = 0x1000;
    477 		}
    478 		/* round size up to a page */
    479 		lf->maplen = pagesize * ((lf->len + pagesize - 1)/pagesize);
    480 
    481 		/*
    482 		 * XXX hack for dealing with empty files; remove when
    483 		 * we're no longer limited by interfacing to the old
    484 		 * logic elsewhere in this file.
    485 		 */
    486 		if (lf->maplen == 0) {
    487 			lf->maplen = pagesize;
    488 		}
    489 
    490 		/*
    491 		 * FUTURE: remove PROT_WRITE when the parser no longer
    492 		 * needs to scribble on the input.
    493 		 */
    494 		lf->buf = mmap(NULL, lf->maplen, PROT_READ|PROT_WRITE,
    495 			       MAP_FILE|MAP_COPY, fd, 0);
    496 		if (lf->buf != MAP_FAILED) {
    497 			/* succeeded */
    498 			if (lf->len == lf->maplen && lf->buf[lf->len - 1] != '\n') {
    499 				char *b = bmake_malloc(lf->len + 1);
    500 				b[lf->len] = '\n';
    501 				memcpy(b, lf->buf, lf->len++);
    502 				munmap(lf->buf, lf->maplen);
    503 				lf->maplen = 0;
    504 				lf->buf = b;
    505 			}
    506 			goto done;
    507 		}
    508 	}
    509 
    510 	/* cannot mmap; load the traditional way */
    511 
    512 	lf->maplen = 0;
    513 	lf->len = 1024;
    514 	lf->buf = bmake_malloc(lf->len);
    515 
    516 	bufpos = 0;
    517 	while (1) {
    518 		assert(bufpos <= lf->len);
    519 		if (bufpos == lf->len) {
    520 			if (lf->len > SIZE_MAX/2) {
    521 				errno = EFBIG;
    522 				Error("%s: file too large", path);
    523 				exit(1);
    524 			}
    525 			lf->len *= 2;
    526 			lf->buf = bmake_realloc(lf->buf, lf->len);
    527 		}
    528 		assert(bufpos < lf->len);
    529 		result = read(fd, lf->buf + bufpos, lf->len - bufpos);
    530 		if (result < 0) {
    531 			Error("%s: read error: %s", path, strerror(errno));
    532 			exit(1);
    533 		}
    534 		if (result == 0) {
    535 			break;
    536 		}
    537 		bufpos += (size_t)result;
    538 	}
    539 	assert(bufpos <= lf->len);
    540 	lf->len = bufpos;
    541 
    542 	/* truncate malloc region to actual length (maybe not useful) */
    543 	if (lf->len > 0) {
    544 		/* as for mmap case, ensure trailing \n */
    545 		if (lf->buf[lf->len - 1] != '\n')
    546 			lf->len++;
    547 		lf->buf = bmake_realloc(lf->buf, lf->len);
    548 		lf->buf[lf->len - 1] = '\n';
    549 	}
    550 
    551 done:
    552 	if (path != NULL) {
    553 		close(fd);
    554 	}
    555 	return lf;
    556 }
    557 
    558 /* old code */
    559 
    560 /* Check if the current character is escaped on the current line. */
    561 static Boolean
    562 ParseIsEscaped(const char *line, const char *c)
    563 {
    564     Boolean active = FALSE;
    565     for (;;) {
    566 	if (line == c)
    567 	    return active;
    568 	if (*--c != '\\')
    569 	    return active;
    570 	active = !active;
    571     }
    572 }
    573 
    574 /* Add the filename and lineno to the GNode so that we remember where it
    575  * was first defined. */
    576 static void
    577 ParseMark(GNode *gn)
    578 {
    579     gn->fname = curFile->fname;
    580     gn->lineno = curFile->lineno;
    581 }
    582 
    583 /* Look in the table of keywords for one matching the given string.
    584  * Return the index of the keyword, or -1 if it isn't there. */
    585 static int
    586 ParseFindKeyword(const char *str)
    587 {
    588     int start, end, cur;
    589     int diff;
    590 
    591     start = 0;
    592     end = sizeof parseKeywords / sizeof parseKeywords[0] - 1;
    593 
    594     do {
    595 	cur = start + (end - start) / 2;
    596 	diff = strcmp(str, parseKeywords[cur].name);
    597 
    598 	if (diff == 0) {
    599 	    return cur;
    600 	} else if (diff < 0) {
    601 	    end = cur - 1;
    602 	} else {
    603 	    start = cur + 1;
    604 	}
    605     } while (start <= end);
    606     return -1;
    607 }
    608 
    609 static void
    610 PrintLocation(FILE *f, const char *filename, size_t lineno)
    611 {
    612 	char dirbuf[MAXPATHLEN+1];
    613 	const char *dir, *base;
    614 	char *dir_freeIt, *base_freeIt;
    615 
    616 	if (*filename == '/' || strcmp(filename, "(stdin)") == 0) {
    617 		(void)fprintf(f, "\"%s\" line %zu: ", filename, lineno);
    618 		return;
    619 	}
    620 
    621 	/* Find out which makefile is the culprit.
    622 	 * We try ${.PARSEDIR} and apply realpath(3) if not absolute. */
    623 
    624 	dir = Var_Value(".PARSEDIR", VAR_GLOBAL, &dir_freeIt);
    625 	if (dir == NULL)
    626 		dir = ".";
    627 	if (*dir != '/')
    628 		dir = realpath(dir, dirbuf);
    629 
    630 	base = Var_Value(".PARSEFILE", VAR_GLOBAL, &base_freeIt);
    631 	if (base == NULL) {
    632 		const char *slash = strrchr(filename, '/');
    633 		base = slash != NULL ? slash + 1 : filename;
    634 	}
    635 
    636 	(void)fprintf(f, "\"%s/%s\" line %zu: ", dir, base, lineno);
    637 	bmake_free(base_freeIt);
    638 	bmake_free(dir_freeIt);
    639 }
    640 
    641 /* Print a parse error message, including location information.
    642  *
    643  * Increment "fatals" if the level is PARSE_FATAL, and continue parsing
    644  * until the end of the current top-level makefile, then exit (see
    645  * Parse_File). */
    646 static void
    647 ParseVErrorInternal(FILE *f, const char *cfname, size_t clineno, int type,
    648     const char *fmt, va_list ap)
    649 {
    650 	static Boolean fatal_warning_error_printed = FALSE;
    651 
    652 	(void)fprintf(f, "%s: ", progname);
    653 
    654 	if (cfname != NULL)
    655 		PrintLocation(f, cfname, clineno);
    656 	if (type == PARSE_WARNING)
    657 		(void)fprintf(f, "warning: ");
    658 	(void)vfprintf(f, fmt, ap);
    659 	(void)fprintf(f, "\n");
    660 	(void)fflush(f);
    661 
    662 	if (type == PARSE_INFO)
    663 		return;
    664 	if (type == PARSE_FATAL || parseWarnFatal)
    665 		fatals++;
    666 	if (parseWarnFatal && !fatal_warning_error_printed) {
    667 		Error("parsing warnings being treated as errors");
    668 		fatal_warning_error_printed = TRUE;
    669 	}
    670 }
    671 
    672 static void
    673 ParseErrorInternal(const char *cfname, size_t clineno, int type,
    674 		   const char *fmt, ...)
    675 {
    676 	va_list ap;
    677 
    678 	va_start(ap, fmt);
    679 	(void)fflush(stdout);
    680 	ParseVErrorInternal(stderr, cfname, clineno, type, fmt, ap);
    681 	va_end(ap);
    682 
    683 	if (debug_file != stderr && debug_file != stdout) {
    684 		va_start(ap, fmt);
    685 		ParseVErrorInternal(debug_file, cfname, clineno, type, fmt, ap);
    686 		va_end(ap);
    687 	}
    688 }
    689 
    690 /* External interface to ParseErrorInternal; uses the default filename and
    691  * line number.
    692  *
    693  * Fmt is given without a trailing newline. */
    694 void
    695 Parse_Error(int type, const char *fmt, ...)
    696 {
    697 	va_list ap;
    698 	const char *fname;
    699 	size_t lineno;
    700 
    701 	if (curFile == NULL) {
    702 		fname = NULL;
    703 		lineno = 0;
    704 	} else {
    705 		fname = curFile->fname;
    706 		lineno = (size_t)curFile->lineno;
    707 	}
    708 
    709 	va_start(ap, fmt);
    710 	(void)fflush(stdout);
    711 	ParseVErrorInternal(stderr, fname, lineno, type, fmt, ap);
    712 	va_end(ap);
    713 
    714 	if (debug_file != stderr && debug_file != stdout) {
    715 		va_start(ap, fmt);
    716 		ParseVErrorInternal(debug_file, fname, lineno, type, fmt, ap);
    717 		va_end(ap);
    718 	}
    719 }
    720 
    721 
    722 /* Parse a .info .warning or .error directive.
    723  *
    724  * The input is the line minus the ".".  We substitute variables, print the
    725  * message and exit(1) (for .error) or just print a warning if the directive
    726  * is malformed.
    727  */
    728 static Boolean
    729 ParseMessage(const char *directive)
    730 {
    731     const char *p = directive;
    732     int mtype = *p == 'i' ? PARSE_INFO :
    733 		*p == 'w' ? PARSE_WARNING : PARSE_FATAL;
    734     char *arg;
    735 
    736     while (ch_isalpha(*p))
    737 	p++;
    738     if (!ch_isspace(*p))
    739 	return FALSE;		/* missing argument */
    740 
    741     cpp_skip_whitespace(&p);
    742     (void)Var_Subst(p, VAR_CMD, VARE_WANTRES, &arg);
    743     /* TODO: handle errors */
    744 
    745     Parse_Error(mtype, "%s", arg);
    746     free(arg);
    747 
    748     if (mtype == PARSE_FATAL) {
    749 	PrintOnError(NULL, NULL);
    750 	exit(1);
    751     }
    752     return TRUE;
    753 }
    754 
    755 /* 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 		 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_Init();
   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_Init();
   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_Init();
   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_Init();
   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_Init();
   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 /* Parse a variable assignment, consisting of a single-word variable name,
   1757  * optional whitespace, an assignment operator, optional whitespace and the
   1758  * variable value.
   1759  *
   1760  * Used for both lines in a file and command line arguments. */
   1761 Boolean
   1762 Parse_IsVar(const char *p, VarAssign *out_var)
   1763 {
   1764     const char *firstSpace = NULL;
   1765     char ch;
   1766     int level = 0;
   1767 
   1768     /* Skip to variable name */
   1769     while (*p == ' ' || *p == '\t')
   1770 	p++;
   1771 
   1772     /* During parsing, the '+' of the '+=' operator is initially parsed
   1773      * as part of the variable name.  It is later corrected, as is the ':sh'
   1774      * modifier. Of these two (nameEnd and op), the earlier one determines the
   1775      * actual end of the variable name. */
   1776     out_var->nameStart = p;
   1777 #ifdef CLEANUP
   1778     out_var->nameEndDraft = NULL;
   1779     out_var->varname = NULL;
   1780     out_var->eq = NULL;
   1781     out_var->op = VAR_NORMAL;
   1782     out_var->value = NULL;
   1783 #endif
   1784 
   1785     /* Scan for one of the assignment operators outside a variable expansion */
   1786     while ((ch = *p++) != 0) {
   1787 	if (ch == '(' || ch == '{') {
   1788 	    level++;
   1789 	    continue;
   1790 	}
   1791 	if (ch == ')' || ch == '}') {
   1792 	    level--;
   1793 	    continue;
   1794 	}
   1795 
   1796 	if (level != 0)
   1797 	    continue;
   1798 
   1799 	if (ch == ' ' || ch == '\t')
   1800 	    if (firstSpace == NULL)
   1801 		firstSpace = p - 1;
   1802 	while (ch == ' ' || ch == '\t')
   1803 	    ch = *p++;
   1804 
   1805 #ifdef SUNSHCMD
   1806 	if (ch == ':' && strncmp(p, "sh", 2) == 0) {
   1807 	    p += 2;
   1808 	    continue;
   1809 	}
   1810 #endif
   1811 	if (ch == '=') {
   1812 	    out_var->eq = p - 1;
   1813 	    out_var->nameEndDraft = firstSpace != NULL ? firstSpace : p - 1;
   1814 	    out_var->op = VAR_NORMAL;
   1815 	    cpp_skip_whitespace(&p);
   1816 	    out_var->value = p;
   1817 	    return TRUE;
   1818 	}
   1819 	if (*p == '=' && (ch == '+' || ch == ':' || ch == '?' || ch == '!')) {
   1820 	    out_var->eq = p;
   1821 	    out_var->nameEndDraft = firstSpace != NULL ? firstSpace : p;
   1822 	    out_var->op = ch == '+' ? VAR_APPEND :
   1823 			  ch == ':' ? VAR_SUBST :
   1824 			  ch == '?' ? VAR_DEFAULT : VAR_SHELL;
   1825 	    p++;
   1826 	    cpp_skip_whitespace(&p);
   1827 	    out_var->value = p;
   1828 	    return TRUE;
   1829 	}
   1830 	if (firstSpace != NULL)
   1831 	    return FALSE;
   1832     }
   1833 
   1834     return FALSE;
   1835 }
   1836 
   1837 /* Determine the assignment operator and adjust the end of the variable
   1838  * name accordingly. */
   1839 static void
   1840 ParseVarassignOp(VarAssign *var)
   1841 {
   1842     const char *op = var->eq;
   1843     const char * const name = var->nameStart;
   1844     VarAssignOp type;
   1845 
   1846     if (op > name && op[-1] == '+') {
   1847 	type = VAR_APPEND;
   1848 	op--;
   1849 
   1850     } else if (op > name && op[-1] == '?') {
   1851 	op--;
   1852 	type = VAR_DEFAULT;
   1853 
   1854     } else if (op > name && op[-1] == ':') {
   1855 	op--;
   1856 	type = VAR_SUBST;
   1857 
   1858     } else if (op > name && op[-1] == '!') {
   1859 	op--;
   1860 	type = VAR_SHELL;
   1861 
   1862     } else {
   1863 	type = VAR_NORMAL;
   1864 #ifdef SUNSHCMD
   1865 	while (op > name && ch_isspace(op[-1]))
   1866 	    op--;
   1867 
   1868 	if (op >= name + 3 && op[-3] == ':' && op[-2] == 's' && op[-1] == 'h') {
   1869 	    type = VAR_SHELL;
   1870 	    op -= 3;
   1871 	}
   1872 #endif
   1873     }
   1874 
   1875     {
   1876 	const char *nameEnd = var->nameEndDraft < op ? var->nameEndDraft : op;
   1877 	var->varname = bmake_strsedup(var->nameStart, nameEnd);
   1878 	var->op = type;
   1879     }
   1880 }
   1881 
   1882 static void
   1883 VarCheckSyntax(VarAssignOp type, const char *uvalue, GNode *ctxt)
   1884 {
   1885     if (DEBUG(LINT)) {
   1886 	if (type != VAR_SUBST && strchr(uvalue, '$') != NULL) {
   1887 	    /* Check for syntax errors such as unclosed expressions or
   1888 	     * unknown modifiers. */
   1889 	    char *expandedValue;
   1890 
   1891 	    (void)Var_Subst(uvalue, ctxt, VARE_NONE, &expandedValue);
   1892 	    /* TODO: handle errors */
   1893 	    free(expandedValue);
   1894 	}
   1895     }
   1896 }
   1897 
   1898 static Boolean
   1899 VarAssign_Eval(VarAssign *var, GNode *ctxt,
   1900 	       const char **out_avalue, void **out_avalue_freeIt)
   1901 {
   1902     const char *uvalue = var->value;
   1903     const char *name = var->varname;
   1904     const VarAssignOp type = var->op;
   1905     const char *avalue = uvalue;
   1906     void *avalue_freeIt = NULL;
   1907 
   1908     if (type == VAR_APPEND) {
   1909 	Var_Append(name, uvalue, ctxt);
   1910     } else if (type == VAR_SUBST) {
   1911 	char *evalue;
   1912 	/*
   1913 	 * Allow variables in the old value to be undefined, but leave their
   1914 	 * expressions alone -- this is done by forcing oldVars to be false.
   1915 	 * XXX: This can cause recursive variables, but that's not hard to do,
   1916 	 * and this allows someone to do something like
   1917 	 *
   1918 	 *  CFLAGS = $(.INCLUDES)
   1919 	 *  CFLAGS := -I.. $(CFLAGS)
   1920 	 *
   1921 	 * And not get an error.
   1922 	 */
   1923 	Boolean oldOldVars = oldVars;
   1924 
   1925 	oldVars = FALSE;
   1926 
   1927 	/*
   1928 	 * make sure that we set the variable the first time to nothing
   1929 	 * so that it gets substituted!
   1930 	 */
   1931 	if (!Var_Exists(name, ctxt))
   1932 	    Var_Set(name, "", ctxt);
   1933 
   1934 	(void)Var_Subst(uvalue, ctxt, VARE_WANTRES|VARE_ASSIGN, &evalue);
   1935 	/* TODO: handle errors */
   1936 	oldVars = oldOldVars;
   1937 	avalue = evalue;
   1938 	avalue_freeIt = evalue;
   1939 
   1940 	Var_Set(name, avalue, ctxt);
   1941     } else if (type == VAR_SHELL) {
   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 	avalue = avalue_freeIt = cmdOut;
   1957 
   1958 	if (errfmt)
   1959 	    Parse_Error(PARSE_WARNING, errfmt, cmd);
   1960 
   1961 	free(cmd_freeIt);
   1962     } else {
   1963 	if (type == VAR_DEFAULT && Var_Exists(var->varname, ctxt)) {
   1964 	    *out_avalue_freeIt = NULL;
   1965 	    return FALSE;
   1966 	}
   1967 
   1968 	/* Normal assignment -- just do it. */
   1969 	Var_Set(name, uvalue, ctxt);
   1970     }
   1971 
   1972     *out_avalue = avalue;
   1973     *out_avalue_freeIt = avalue_freeIt;
   1974     return TRUE;
   1975 }
   1976 
   1977 static void
   1978 VarAssignSpecial(const char *name, const char *avalue)
   1979 {
   1980     if (strcmp(name, MAKEOVERRIDES) == 0)
   1981 	Main_ExportMAKEFLAGS(FALSE);	/* re-export MAKEFLAGS */
   1982     else if (strcmp(name, ".CURDIR") == 0) {
   1983 	/*
   1984 	 * Someone is being (too?) clever...
   1985 	 * Let's pretend they know what they are doing and
   1986 	 * re-initialize the 'cur' CachedDir.
   1987 	 */
   1988 	Dir_InitCur(avalue);
   1989 	Dir_SetPATH();
   1990     } else if (strcmp(name, MAKE_JOB_PREFIX) == 0) {
   1991 	Job_SetPrefix();
   1992     } else if (strcmp(name, MAKE_EXPORTED) == 0) {
   1993 	Var_Export(avalue, FALSE);
   1994     }
   1995 }
   1996 
   1997 /* Take the variable assignment in the passed line and execute it.
   1998  *
   1999  * Note: There is a lexical ambiguity with assignment modifier characters
   2000  * in variable names. This routine interprets the character before the =
   2001  * as a modifier. Therefore, an assignment like
   2002  *	C++=/usr/bin/CC
   2003  * is interpreted as "C+ +=" instead of "C++ =".
   2004  *
   2005  * Input:
   2006  *	p		A line guaranteed to be a variable assignment
   2007  *			(see Parse_IsVar).
   2008  *	ctxt		Context in which to do the assignment
   2009  */
   2010 void
   2011 Parse_DoVar(VarAssign *var, GNode *ctxt)
   2012 {
   2013     const char *avalue;		/* actual value (maybe expanded) */
   2014     void *avalue_freeIt;
   2015 
   2016     ParseVarassignOp(var);
   2017 
   2018     VarCheckSyntax(var->op, var->value, ctxt);
   2019     if (VarAssign_Eval(var, ctxt, &avalue, &avalue_freeIt))
   2020 	VarAssignSpecial(var->varname, avalue);
   2021 
   2022     free(avalue_freeIt);
   2023     free(var->varname);
   2024 }
   2025 
   2026 
   2027 /*
   2028  * ParseMaybeSubMake --
   2029  *	Scan the command string to see if it a possible submake node
   2030  * Input:
   2031  *	cmd		the command to scan
   2032  * Results:
   2033  *	TRUE if the command is possibly a submake, FALSE if not.
   2034  */
   2035 static Boolean
   2036 ParseMaybeSubMake(const char *cmd)
   2037 {
   2038     size_t i;
   2039     static struct {
   2040 	const char *name;
   2041 	size_t len;
   2042     } vals[] = {
   2043 #define MKV(A)	{	A, sizeof(A) - 1	}
   2044 	MKV("${MAKE}"),
   2045 	MKV("${.MAKE}"),
   2046 	MKV("$(MAKE)"),
   2047 	MKV("$(.MAKE)"),
   2048 	MKV("make"),
   2049     };
   2050     for (i = 0; i < sizeof vals / sizeof vals[0]; i++) {
   2051 	char *ptr;
   2052 	if ((ptr = strstr(cmd, vals[i].name)) == NULL)
   2053 	    continue;
   2054 	if ((ptr == cmd || !ch_isalnum(ptr[-1]))
   2055 	    && !ch_isalnum(ptr[vals[i].len]))
   2056 	    return TRUE;
   2057     }
   2058     return FALSE;
   2059 }
   2060 
   2061 /* Append the command to the target node.
   2062  *
   2063  * The node may be marked as a submake node if the command is determined to
   2064  * be that. */
   2065 static void
   2066 ParseAddCmd(GNode *gn, char *cmd)
   2067 {
   2068     /* Add to last (ie current) cohort for :: targets */
   2069     if ((gn->type & OP_DOUBLEDEP) && gn->cohorts->last != NULL)
   2070 	gn = gn->cohorts->last->datum;
   2071 
   2072     /* if target already supplied, ignore commands */
   2073     if (!(gn->type & OP_HAS_COMMANDS)) {
   2074 	Lst_Append(gn->commands, cmd);
   2075 	if (ParseMaybeSubMake(cmd))
   2076 	    gn->type |= OP_SUBMAKE;
   2077 	ParseMark(gn);
   2078     } else {
   2079 #if 0
   2080 	/* XXX: We cannot do this until we fix the tree */
   2081 	Lst_Append(gn->commands, cmd);
   2082 	Parse_Error(PARSE_WARNING,
   2083 		     "overriding commands for target \"%s\"; "
   2084 		     "previous commands defined at %s: %d ignored",
   2085 		     gn->name, gn->fname, gn->lineno);
   2086 #else
   2087 	Parse_Error(PARSE_WARNING,
   2088 		    "duplicate script for target \"%s\" ignored",
   2089 		    gn->name);
   2090 	ParseErrorInternal(gn->fname, (size_t)gn->lineno, PARSE_WARNING,
   2091 			   "using previous script for \"%s\" defined here",
   2092 			   gn->name);
   2093 #endif
   2094     }
   2095 }
   2096 
   2097 /* Add a directory to the path searched for included makefiles bracketed
   2098  * by double-quotes. */
   2099 void
   2100 Parse_AddIncludeDir(const char *dir)
   2101 {
   2102     (void)Dir_AddDir(parseIncPath, dir);
   2103 }
   2104 
   2105 /* Push to another file.
   2106  *
   2107  * The input is the line minus the '.'. A file spec is a string enclosed in
   2108  * <> or "". The <> file is looked for only in sysIncPath. The "" file is
   2109  * first searched in the parsedir and then in the directories specified by
   2110  * the -I command line options.
   2111  */
   2112 static void
   2113 Parse_include_file(char *file, Boolean isSystem, Boolean depinc, int silent)
   2114 {
   2115     struct loadedfile *lf;
   2116     char *fullname;		/* full pathname of file */
   2117     char *newName;
   2118     char *prefEnd, *incdir;
   2119     int fd;
   2120     int i;
   2121 
   2122     /*
   2123      * Now we know the file's name and its search path, we attempt to
   2124      * find the durn thing. A return of NULL indicates the file don't
   2125      * exist.
   2126      */
   2127     fullname = file[0] == '/' ? bmake_strdup(file) : NULL;
   2128 
   2129     if (fullname == NULL && !isSystem) {
   2130 	/*
   2131 	 * Include files contained in double-quotes are first searched for
   2132 	 * relative to the including file's location. We don't want to
   2133 	 * cd there, of course, so we just tack on the old file's
   2134 	 * leading path components and call Dir_FindFile to see if
   2135 	 * we can locate the beast.
   2136 	 */
   2137 
   2138 	incdir = bmake_strdup(curFile->fname);
   2139 	prefEnd = strrchr(incdir, '/');
   2140 	if (prefEnd != NULL) {
   2141 	    *prefEnd = '\0';
   2142 	    /* Now do lexical processing of leading "../" on the filename */
   2143 	    for (i = 0; strncmp(file + i, "../", 3) == 0; i += 3) {
   2144 		prefEnd = strrchr(incdir + 1, '/');
   2145 		if (prefEnd == NULL || strcmp(prefEnd, "/..") == 0)
   2146 		    break;
   2147 		*prefEnd = '\0';
   2148 	    }
   2149 	    newName = str_concat3(incdir, "/", file + i);
   2150 	    fullname = Dir_FindFile(newName, parseIncPath);
   2151 	    if (fullname == NULL)
   2152 		fullname = Dir_FindFile(newName, dirSearchPath);
   2153 	    free(newName);
   2154 	}
   2155 	free(incdir);
   2156 
   2157 	if (fullname == NULL) {
   2158 	    /*
   2159 	     * Makefile wasn't found in same directory as included makefile.
   2160 	     * Search for it first on the -I search path,
   2161 	     * then on the .PATH search path, if not found in a -I directory.
   2162 	     * If we have a suffix specific path we should use that.
   2163 	     */
   2164 	    char *suff;
   2165 	    SearchPath *suffPath = NULL;
   2166 
   2167 	    if ((suff = strrchr(file, '.'))) {
   2168 		suffPath = Suff_GetPath(suff);
   2169 		if (suffPath != NULL) {
   2170 		    fullname = Dir_FindFile(file, suffPath);
   2171 		}
   2172 	    }
   2173 	    if (fullname == NULL) {
   2174 		fullname = Dir_FindFile(file, parseIncPath);
   2175 		if (fullname == NULL) {
   2176 		    fullname = Dir_FindFile(file, dirSearchPath);
   2177 		}
   2178 	    }
   2179 	}
   2180     }
   2181 
   2182     /* Looking for a system file or file still not found */
   2183     if (fullname == NULL) {
   2184 	/*
   2185 	 * Look for it on the system path
   2186 	 */
   2187 	SearchPath *path = Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath;
   2188 	fullname = Dir_FindFile(file, path);
   2189     }
   2190 
   2191     if (fullname == NULL) {
   2192 	if (!silent)
   2193 	    Parse_Error(PARSE_FATAL, "Could not find %s", file);
   2194 	return;
   2195     }
   2196 
   2197     /* Actually open the file... */
   2198     fd = open(fullname, O_RDONLY);
   2199     if (fd == -1) {
   2200 	if (!silent)
   2201 	    Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
   2202 	free(fullname);
   2203 	return;
   2204     }
   2205 
   2206     /* load it */
   2207     lf = loadfile(fullname, fd);
   2208 
   2209     /* Start reading from this file next */
   2210     Parse_SetInput(fullname, 0, -1, loadedfile_nextbuf, lf);
   2211     curFile->lf = lf;
   2212     if (depinc)
   2213 	doing_depend = depinc;	/* only turn it on */
   2214 }
   2215 
   2216 static void
   2217 ParseDoInclude(char *line)
   2218 {
   2219     char endc;			/* the character which ends the file spec */
   2220     char *cp;			/* current position in file spec */
   2221     int silent = *line != 'i';
   2222     char *file = line + (silent ? 8 : 7);
   2223 
   2224     /* Skip to delimiter character so we know where to look */
   2225     while (*file == ' ' || *file == '\t')
   2226 	file++;
   2227 
   2228     if (*file != '"' && *file != '<') {
   2229 	Parse_Error(PARSE_FATAL,
   2230 		    ".include filename must be delimited by '\"' or '<'");
   2231 	return;
   2232     }
   2233 
   2234     /*
   2235      * Set the search path on which to find the include file based on the
   2236      * characters which bracket its name. Angle-brackets imply it's
   2237      * a system Makefile while double-quotes imply it's a user makefile
   2238      */
   2239     if (*file == '<') {
   2240 	endc = '>';
   2241     } else {
   2242 	endc = '"';
   2243     }
   2244 
   2245     /* Skip to matching delimiter */
   2246     for (cp = ++file; *cp && *cp != endc; cp++)
   2247 	continue;
   2248 
   2249     if (*cp != endc) {
   2250 	Parse_Error(PARSE_FATAL,
   2251 		    "Unclosed %cinclude filename. '%c' expected",
   2252 		    '.', endc);
   2253 	return;
   2254     }
   2255     *cp = '\0';
   2256 
   2257     /*
   2258      * Substitute for any variables in the file name before trying to
   2259      * find the thing.
   2260      */
   2261     (void)Var_Subst(file, VAR_CMD, VARE_WANTRES, &file);
   2262     /* TODO: handle errors */
   2263 
   2264     Parse_include_file(file, endc == '>', *line == 'd', silent);
   2265     free(file);
   2266 }
   2267 
   2268 /* Split filename into dirname + basename, then assign these to the
   2269  * given variables. */
   2270 static void
   2271 SetFilenameVars(const char *filename, const char *dirvar, const char *filevar)
   2272 {
   2273     const char *slash, *dirname, *basename;
   2274     void *freeIt;
   2275 
   2276     slash = strrchr(filename, '/');
   2277     if (slash == NULL) {
   2278 	dirname = curdir;
   2279 	basename = filename;
   2280 	freeIt = NULL;
   2281     } else {
   2282 	dirname = freeIt = bmake_strsedup(filename, slash);
   2283 	basename = slash + 1;
   2284     }
   2285 
   2286     Var_Set(dirvar, dirname, VAR_GLOBAL);
   2287     Var_Set(filevar, basename, VAR_GLOBAL);
   2288 
   2289     DEBUG5(PARSE, "%s: ${%s} = `%s' ${%s} = `%s'\n",
   2290 	   __func__, dirvar, dirname, filevar, basename);
   2291     free(freeIt);
   2292 }
   2293 
   2294 /* Return the immediately including file.
   2295  *
   2296  * This is made complicated since the .for loop is implemented as a special
   2297  * kind of .include; see For_Run. */
   2298 static const char *
   2299 GetActuallyIncludingFile(void)
   2300 {
   2301     size_t i;
   2302 
   2303     /* XXX: Stack was supposed to be an opaque data structure. */
   2304     for (i = includes.len; i > 0; i--) {
   2305 	IFile *parent = includes.items[i - 1];
   2306 	IFile *child = i < includes.len ? includes.items[i] : curFile;
   2307 	if (!child->fromForLoop)
   2308 	    return parent->fname;
   2309     }
   2310     return NULL;
   2311 }
   2312 
   2313 /* Set .PARSEDIR, .PARSEFILE, .INCLUDEDFROMDIR and .INCLUDEDFROMFILE. */
   2314 static void
   2315 ParseSetParseFile(const char *filename)
   2316 {
   2317     const char *including;
   2318 
   2319     SetFilenameVars(filename, ".PARSEDIR", ".PARSEFILE");
   2320 
   2321     including = GetActuallyIncludingFile();
   2322     if (including != NULL) {
   2323 	SetFilenameVars(including,
   2324 			".INCLUDEDFROMDIR", ".INCLUDEDFROMFILE");
   2325     } else {
   2326 	Var_Delete(".INCLUDEDFROMDIR", VAR_GLOBAL);
   2327 	Var_Delete(".INCLUDEDFROMFILE", VAR_GLOBAL);
   2328     }
   2329 }
   2330 
   2331 /* Track the makefiles we read - so makefiles can set dependencies on them.
   2332  * Avoid adding anything more than once. */
   2333 static void
   2334 ParseTrackInput(const char *name)
   2335 {
   2336     char *fp = NULL;
   2337 
   2338     const char *old = Var_Value(MAKE_MAKEFILES, VAR_GLOBAL, &fp);
   2339     if (old) {
   2340 	size_t name_len = strlen(name);
   2341 	const char *ep = old + strlen(old) - name_len;
   2342 	/* does it contain name? */
   2343 	for (; old != NULL; old = strchr(old, ' ')) {
   2344 	    if (*old == ' ')
   2345 		old++;
   2346 	    if (old >= ep)
   2347 		break;		/* cannot contain name */
   2348 	    if (memcmp(old, name, name_len) == 0 &&
   2349 		(old[name_len] == '\0' || old[name_len] == ' '))
   2350 		goto cleanup;
   2351 	}
   2352     }
   2353     Var_Append(MAKE_MAKEFILES, name, VAR_GLOBAL);
   2354 cleanup:
   2355     bmake_free(fp);
   2356 }
   2357 
   2358 
   2359 /* Start Parsing from the given source.
   2360  *
   2361  * The given file is added to the includes stack. */
   2362 void
   2363 Parse_SetInput(const char *name, int line, int fd,
   2364 	       char *(*nextbuf)(void *, size_t *), void *arg)
   2365 {
   2366     char *buf;
   2367     size_t len;
   2368     Boolean fromForLoop = name == NULL;
   2369 
   2370     if (fromForLoop)
   2371 	name = curFile->fname;
   2372     else
   2373 	ParseTrackInput(name);
   2374 
   2375     if (DEBUG(PARSE))
   2376 	debug_printf("%s: file %s, line %d, fd %d, nextbuf %s, arg %p\n",
   2377 		     __func__, name, line, fd,
   2378 		     nextbuf == loadedfile_nextbuf ? "loadedfile" : "other",
   2379 		     arg);
   2380 
   2381     if (fd == -1 && nextbuf == NULL)
   2382 	/* sanity */
   2383 	return;
   2384 
   2385     if (curFile != NULL)
   2386 	/* Save existing file info */
   2387 	Stack_Push(&includes, curFile);
   2388 
   2389     /* Allocate and fill in new structure */
   2390     curFile = bmake_malloc(sizeof *curFile);
   2391 
   2392     /*
   2393      * Once the previous state has been saved, we can get down to reading
   2394      * the new file. We set up the name of the file to be the absolute
   2395      * name of the include file so error messages refer to the right
   2396      * place.
   2397      */
   2398     curFile->fname = bmake_strdup(name);
   2399     curFile->fromForLoop = fromForLoop;
   2400     curFile->lineno = line;
   2401     curFile->first_lineno = line;
   2402     curFile->nextbuf = nextbuf;
   2403     curFile->nextbuf_arg = arg;
   2404     curFile->lf = NULL;
   2405     curFile->depending = doing_depend;	/* restore this on EOF */
   2406 
   2407     assert(nextbuf != NULL);
   2408 
   2409     /* Get first block of input data */
   2410     buf = curFile->nextbuf(curFile->nextbuf_arg, &len);
   2411     if (buf == NULL) {
   2412 	/* Was all a waste of time ... */
   2413 	if (curFile->fname)
   2414 	    free(curFile->fname);
   2415 	free(curFile);
   2416 	return;
   2417     }
   2418     curFile->P_str = buf;
   2419     curFile->P_ptr = buf;
   2420     curFile->P_end = buf + len;
   2421 
   2422     curFile->cond_depth = Cond_save_depth();
   2423     ParseSetParseFile(name);
   2424 }
   2425 
   2426 /* Check if the directive is an include directive. */
   2427 static Boolean
   2428 IsInclude(const char *dir, Boolean sysv)
   2429 {
   2430 	if (dir[0] == 's' || dir[0] == '-' || (dir[0] == 'd' && !sysv))
   2431 		dir++;
   2432 
   2433 	if (strncmp(dir, "include", 7) != 0)
   2434 		return FALSE;
   2435 
   2436 	/* Space is not mandatory for BSD .include */
   2437 	return !sysv || ch_isspace(dir[7]);
   2438 }
   2439 
   2440 
   2441 #ifdef SYSVINCLUDE
   2442 /* Check if the line is a SYSV include directive. */
   2443 static Boolean
   2444 IsSysVInclude(const char *line)
   2445 {
   2446 	const char *p;
   2447 
   2448 	if (!IsInclude(line, TRUE))
   2449 		return FALSE;
   2450 
   2451 	/* Avoid interpreting a dependency line as an include */
   2452 	for (p = line; (p = strchr(p, ':')) != NULL;) {
   2453 		if (*++p == '\0') {
   2454 			/* end of line -> dependency */
   2455 			return FALSE;
   2456 		}
   2457 		if (*p == ':' || ch_isspace(*p)) {
   2458 			/* :: operator or ': ' -> dependency */
   2459 			return FALSE;
   2460 		}
   2461 	}
   2462 	return TRUE;
   2463 }
   2464 
   2465 /* Push to another file.  The line points to the word "include". */
   2466 static void
   2467 ParseTraditionalInclude(char *line)
   2468 {
   2469     char *cp;			/* current position in file spec */
   2470     int done = 0;
   2471     int silent = line[0] != 'i';
   2472     char *file = line + (silent ? 8 : 7);
   2473     char *all_files;
   2474 
   2475     DEBUG2(PARSE, "%s: %s\n", __func__, file);
   2476 
   2477     pp_skip_whitespace(&file);
   2478 
   2479     /*
   2480      * Substitute for any variables in the file name before trying to
   2481      * find the thing.
   2482      */
   2483     (void)Var_Subst(file, VAR_CMD, VARE_WANTRES, &all_files);
   2484     /* TODO: handle errors */
   2485 
   2486     if (*file == '\0') {
   2487 	Parse_Error(PARSE_FATAL, "Filename missing from \"include\"");
   2488 	goto out;
   2489     }
   2490 
   2491     for (file = all_files; !done; file = cp + 1) {
   2492 	/* Skip to end of line or next whitespace */
   2493 	for (cp = file; *cp && !ch_isspace(*cp); cp++)
   2494 	    continue;
   2495 
   2496 	if (*cp)
   2497 	    *cp = '\0';
   2498 	else
   2499 	    done = 1;
   2500 
   2501 	Parse_include_file(file, FALSE, FALSE, silent);
   2502     }
   2503 out:
   2504     free(all_files);
   2505 }
   2506 #endif
   2507 
   2508 #ifdef GMAKEEXPORT
   2509 /* Parse "export <variable>=<value>", and actually export it. */
   2510 static void
   2511 ParseGmakeExport(char *line)
   2512 {
   2513     char *variable = line + 6;
   2514     char *value;
   2515 
   2516     DEBUG2(PARSE, "%s: %s\n", __func__, variable);
   2517 
   2518     pp_skip_whitespace(&variable);
   2519 
   2520     for (value = variable; *value && *value != '='; value++)
   2521 	continue;
   2522 
   2523     if (*value != '=') {
   2524 	Parse_Error(PARSE_FATAL,
   2525 		    "Variable/Value missing from \"export\"");
   2526 	return;
   2527     }
   2528     *value++ = '\0';		/* terminate variable */
   2529 
   2530     /*
   2531      * Expand the value before putting it in the environment.
   2532      */
   2533     (void)Var_Subst(value, VAR_CMD, VARE_WANTRES, &value);
   2534     /* TODO: handle errors */
   2535 
   2536     setenv(variable, value, 1);
   2537     free(value);
   2538 }
   2539 #endif
   2540 
   2541 /* Called when EOF is reached in the current file. If we were reading an
   2542  * include file, the includes stack is popped and things set up to go back
   2543  * to reading the previous file at the previous location.
   2544  *
   2545  * Results:
   2546  *	TRUE to continue parsing, i.e. it had only reached the end of an
   2547  *	included file, FALSE if the main file has been parsed completely.
   2548  */
   2549 static Boolean
   2550 ParseEOF(void)
   2551 {
   2552     char *ptr;
   2553     size_t len;
   2554 
   2555     assert(curFile->nextbuf != NULL);
   2556 
   2557     doing_depend = curFile->depending;	/* restore this */
   2558     /* get next input buffer, if any */
   2559     ptr = curFile->nextbuf(curFile->nextbuf_arg, &len);
   2560     curFile->P_ptr = ptr;
   2561     curFile->P_str = ptr;
   2562     curFile->P_end = ptr + len;
   2563     curFile->lineno = curFile->first_lineno;
   2564     if (ptr != NULL) {
   2565 	/* Iterate again */
   2566 	return TRUE;
   2567     }
   2568 
   2569     /* Ensure the makefile (or loop) didn't have mismatched conditionals */
   2570     Cond_restore_depth(curFile->cond_depth);
   2571 
   2572     if (curFile->lf != NULL) {
   2573 	loadedfile_destroy(curFile->lf);
   2574 	curFile->lf = NULL;
   2575     }
   2576 
   2577     /* Dispose of curFile info */
   2578     /* Leak curFile->fname because all the gnodes have pointers to it */
   2579     free(curFile->P_str);
   2580     free(curFile);
   2581 
   2582     if (Stack_IsEmpty(&includes)) {
   2583 	curFile = NULL;
   2584 	/* We've run out of input */
   2585 	Var_Delete(".PARSEDIR", VAR_GLOBAL);
   2586 	Var_Delete(".PARSEFILE", VAR_GLOBAL);
   2587 	Var_Delete(".INCLUDEDFROMDIR", VAR_GLOBAL);
   2588 	Var_Delete(".INCLUDEDFROMFILE", VAR_GLOBAL);
   2589 	return FALSE;
   2590     }
   2591 
   2592     curFile = Stack_Pop(&includes);
   2593     DEBUG2(PARSE, "ParseEOF: returning to file %s, line %d\n",
   2594 	   curFile->fname, curFile->lineno);
   2595 
   2596     ParseSetParseFile(curFile->fname);
   2597     return TRUE;
   2598 }
   2599 
   2600 #define PARSE_RAW 1
   2601 #define PARSE_SKIP 2
   2602 
   2603 static char *
   2604 ParseGetLine(int flags)
   2605 {
   2606     IFile *cf = curFile;
   2607     char *ptr;
   2608     char ch;
   2609     char *line;
   2610     char *line_end;
   2611     char *escaped;
   2612     char *comment;
   2613     char *tp;
   2614 
   2615     /* Loop through blank lines and comment lines */
   2616     for (;;) {
   2617 	cf->lineno++;
   2618 	line = cf->P_ptr;
   2619 	ptr = line;
   2620 	line_end = line;
   2621 	escaped = NULL;
   2622 	comment = NULL;
   2623 	for (;;) {
   2624 	    if (cf->P_end != NULL && ptr == cf->P_end) {
   2625 		/* end of buffer */
   2626 		ch = 0;
   2627 		break;
   2628 	    }
   2629 	    ch = *ptr;
   2630 	    if (ch == 0 || (ch == '\\' && ptr[1] == 0)) {
   2631 		if (cf->P_end == NULL)
   2632 		    /* End of string (aka for loop) data */
   2633 		    break;
   2634 		/* see if there is more we can parse */
   2635 		while (ptr++ < cf->P_end) {
   2636 		    if ((ch = *ptr) == '\n') {
   2637 			if (ptr > line && ptr[-1] == '\\')
   2638 			    continue;
   2639 			Parse_Error(PARSE_WARNING,
   2640 				    "Zero byte read from file, "
   2641 				    "skipping rest of line.");
   2642 			break;
   2643 		    }
   2644 		}
   2645 		if (cf->nextbuf != NULL) {
   2646 		    /*
   2647 		     * End of this buffer; return EOF and outer logic
   2648 		     * will get the next one. (eww)
   2649 		     */
   2650 		    break;
   2651 		}
   2652 		Parse_Error(PARSE_FATAL, "Zero byte read from file");
   2653 		return NULL;
   2654 	    }
   2655 
   2656 	    if (ch == '\\') {
   2657 		/* Don't treat next character as special, remember first one */
   2658 		if (escaped == NULL)
   2659 		    escaped = ptr;
   2660 		if (ptr[1] == '\n')
   2661 		    cf->lineno++;
   2662 		ptr += 2;
   2663 		line_end = ptr;
   2664 		continue;
   2665 	    }
   2666 	    if (ch == '#' && comment == NULL) {
   2667 		/* Remember first '#' for comment stripping */
   2668 		/* Unless previous char was '[', as in modifier :[#] */
   2669 		if (!(ptr > line && ptr[-1] == '['))
   2670 		    comment = line_end;
   2671 	    }
   2672 	    ptr++;
   2673 	    if (ch == '\n')
   2674 		break;
   2675 	    if (!ch_isspace(ch))
   2676 		/* We are not interested in trailing whitespace */
   2677 		line_end = ptr;
   2678 	}
   2679 
   2680 	/* Save next 'to be processed' location */
   2681 	cf->P_ptr = ptr;
   2682 
   2683 	/* Check we have a non-comment, non-blank line */
   2684 	if (line_end == line || comment == line) {
   2685 	    if (ch == 0)
   2686 		/* At end of file */
   2687 		return NULL;
   2688 	    /* Parse another line */
   2689 	    continue;
   2690 	}
   2691 
   2692 	/* We now have a line of data */
   2693 	*line_end = 0;
   2694 
   2695 	if (flags & PARSE_RAW) {
   2696 	    /* Leave '\' (etc) in line buffer (eg 'for' lines) */
   2697 	    return line;
   2698 	}
   2699 
   2700 	if (flags & PARSE_SKIP) {
   2701 	    /* Completely ignore non-directives */
   2702 	    if (line[0] != '.')
   2703 		continue;
   2704 	    /* We could do more of the .else/.elif/.endif checks here */
   2705 	}
   2706 	break;
   2707     }
   2708 
   2709     /* Brutally ignore anything after a non-escaped '#' in non-commands */
   2710     if (comment != NULL && line[0] != '\t') {
   2711 	line_end = comment;
   2712 	*line_end = 0;
   2713     }
   2714 
   2715     /* If we didn't see a '\\' then the in-situ data is fine */
   2716     if (escaped == NULL)
   2717 	return line;
   2718 
   2719     /* Remove escapes from '\n' and '#' */
   2720     tp = ptr = escaped;
   2721     escaped = line;
   2722     for (; ; *tp++ = ch) {
   2723 	ch = *ptr++;
   2724 	if (ch != '\\') {
   2725 	    if (ch == 0)
   2726 		break;
   2727 	    continue;
   2728 	}
   2729 
   2730 	ch = *ptr++;
   2731 	if (ch == 0) {
   2732 	    /* Delete '\\' at end of buffer */
   2733 	    tp--;
   2734 	    break;
   2735 	}
   2736 
   2737 	if (ch == '#' && line[0] != '\t')
   2738 	    /* Delete '\\' from before '#' on non-command lines */
   2739 	    continue;
   2740 
   2741 	if (ch != '\n') {
   2742 	    /* Leave '\\' in buffer for later */
   2743 	    *tp++ = '\\';
   2744 	    /* Make sure we don't delete an escaped ' ' from the line end */
   2745 	    escaped = tp + 1;
   2746 	    continue;
   2747 	}
   2748 
   2749 	/* Escaped '\n' replace following whitespace with a single ' ' */
   2750 	while (ptr[0] == ' ' || ptr[0] == '\t')
   2751 	    ptr++;
   2752 	ch = ' ';
   2753     }
   2754 
   2755     /* Delete any trailing spaces - eg from empty continuations */
   2756     while (tp > escaped && ch_isspace(tp[-1]))
   2757 	tp--;
   2758 
   2759     *tp = 0;
   2760     return line;
   2761 }
   2762 
   2763 /* Read an entire line from the input file. Called only by Parse_File.
   2764  *
   2765  * Results:
   2766  *	A line without its newline.
   2767  *
   2768  * Side Effects:
   2769  *	Only those associated with reading a character
   2770  */
   2771 static char *
   2772 ParseReadLine(void)
   2773 {
   2774     char *line;			/* Result */
   2775     int lineno;			/* Saved line # */
   2776     int rval;
   2777 
   2778     for (;;) {
   2779 	line = ParseGetLine(0);
   2780 	if (line == NULL)
   2781 	    return NULL;
   2782 
   2783 	if (line[0] != '.')
   2784 	    return line;
   2785 
   2786 	/*
   2787 	 * The line might be a conditional. Ask the conditional module
   2788 	 * about it and act accordingly
   2789 	 */
   2790 	switch (Cond_EvalLine(line)) {
   2791 	case COND_SKIP:
   2792 	    /* Skip to next conditional that evaluates to COND_PARSE.  */
   2793 	    do {
   2794 		line = ParseGetLine(PARSE_SKIP);
   2795 	    } while (line && Cond_EvalLine(line) != COND_PARSE);
   2796 	    if (line == NULL)
   2797 		break;
   2798 	    continue;
   2799 	case COND_PARSE:
   2800 	    continue;
   2801 	case COND_INVALID:    /* Not a conditional line */
   2802 	    /* Check for .for loops */
   2803 	    rval = For_Eval(line);
   2804 	    if (rval == 0)
   2805 		/* Not a .for line */
   2806 		break;
   2807 	    if (rval < 0)
   2808 		/* Syntax error - error printed, ignore line */
   2809 		continue;
   2810 	    /* Start of a .for loop */
   2811 	    lineno = curFile->lineno;
   2812 	    /* Accumulate loop lines until matching .endfor */
   2813 	    do {
   2814 		line = ParseGetLine(PARSE_RAW);
   2815 		if (line == NULL) {
   2816 		    Parse_Error(PARSE_FATAL,
   2817 				"Unexpected end of file in for loop.");
   2818 		    break;
   2819 		}
   2820 	    } while (For_Accum(line));
   2821 	    /* Stash each iteration as a new 'input file' */
   2822 	    For_Run(lineno);
   2823 	    /* Read next line from for-loop buffer */
   2824 	    continue;
   2825 	}
   2826 	return line;
   2827     }
   2828 }
   2829 
   2830 static void
   2831 FinishDependencyGroup(void)
   2832 {
   2833     if (targets != NULL) {
   2834 	GNodeListNode *ln;
   2835 	for (ln = targets->first; ln != NULL; ln = ln->next) {
   2836 	    GNode *gn = ln->datum;
   2837 
   2838 	    Suff_EndTransform(gn);
   2839 
   2840 	    /* Mark the target as already having commands if it does, to
   2841 	     * keep from having shell commands on multiple dependency lines. */
   2842 	    if (!Lst_IsEmpty(gn->commands))
   2843 		gn->type |= OP_HAS_COMMANDS;
   2844 	}
   2845 
   2846 	Lst_Free(targets);
   2847 	targets = NULL;
   2848     }
   2849 }
   2850 
   2851 /* Add the command to each target from the current dependency spec. */
   2852 static void
   2853 ParseLine_ShellCommand(const char *p)
   2854 {
   2855     cpp_skip_whitespace(&p);
   2856     if (*p == '\0')
   2857 	return;			/* skip empty commands */
   2858 
   2859     if (targets == NULL) {
   2860 	Parse_Error(PARSE_FATAL, "Unassociated shell command \"%s\"", p);
   2861 	return;
   2862     }
   2863 
   2864     {
   2865 	char *cmd = bmake_strdup(p);
   2866 	GNodeListNode *ln;
   2867 
   2868 	for (ln = targets->first; ln != NULL; ln = ln->next) {
   2869 	    GNode *gn = ln->datum;
   2870 	    ParseAddCmd(gn, cmd);
   2871 	}
   2872 #ifdef CLEANUP
   2873 	Lst_Append(targCmds, cmd);
   2874 #endif
   2875     }
   2876 }
   2877 
   2878 static Boolean
   2879 ParseDirective(char *line)
   2880 {
   2881     char *cp;
   2882 
   2883     if (*line == '.') {
   2884 	/*
   2885 	 * Lines that begin with the special character may be
   2886 	 * include or undef directives.
   2887 	 * On the other hand they can be suffix rules (.c.o: ...)
   2888 	 * or just dependencies for filenames that start '.'.
   2889 	 */
   2890 	cp = line + 1;
   2891 	pp_skip_whitespace(&cp);
   2892 	if (IsInclude(cp, FALSE)) {
   2893 	    ParseDoInclude(cp);
   2894 	    return TRUE;
   2895 	}
   2896 	if (strncmp(cp, "undef", 5) == 0) {
   2897 	    const char *varname;
   2898 	    cp += 5;
   2899 	    pp_skip_whitespace(&cp);
   2900 	    varname = cp;
   2901 	    for (; !ch_isspace(*cp) && *cp != '\0'; cp++)
   2902 		continue;
   2903 	    *cp = '\0';
   2904 	    Var_Delete(varname, VAR_GLOBAL);
   2905 	    /* TODO: undefine all variables, not only the first */
   2906 	    /* TODO: use Str_Words, like everywhere else */
   2907 	    return TRUE;
   2908 	} else if (strncmp(cp, "export", 6) == 0) {
   2909 	    cp += 6;
   2910 	    pp_skip_whitespace(&cp);
   2911 	    Var_Export(cp, TRUE);
   2912 	    return TRUE;
   2913 	} else if (strncmp(cp, "unexport", 8) == 0) {
   2914 	    Var_UnExport(cp);
   2915 	    return TRUE;
   2916 	} else if (strncmp(cp, "info", 4) == 0 ||
   2917 		   strncmp(cp, "error", 5) == 0 ||
   2918 		   strncmp(cp, "warning", 7) == 0) {
   2919 	    if (ParseMessage(cp))
   2920 		return TRUE;
   2921 	}
   2922     }
   2923     return FALSE;
   2924 }
   2925 
   2926 static Boolean
   2927 ParseVarassign(const char *line)
   2928 {
   2929     VarAssign var;
   2930     if (Parse_IsVar(line, &var)) {
   2931 	FinishDependencyGroup();
   2932 	Parse_DoVar(&var, VAR_GLOBAL);
   2933 	return TRUE;
   2934     }
   2935     return FALSE;
   2936 }
   2937 
   2938 static char *
   2939 FindSemicolon(char *p)
   2940 {
   2941     int level = 0;
   2942 
   2943     for (; *p != '\0'; p++) {
   2944 	if (*p == '\\' && p[1] != '\0') {
   2945 	    p++;
   2946 	    continue;
   2947 	}
   2948 
   2949 	if (*p == '$' && (p[1] == '(' || p[1] == '{')) {
   2950 	    level++;
   2951 	    continue;
   2952 	}
   2953 
   2954 	if (level > 0 && (*p == ')' || *p == '}')) {
   2955 	    level--;
   2956 	    continue;
   2957 	}
   2958 
   2959 	if (level == 0 && *p == ';') {
   2960 	    break;
   2961 	}
   2962     }
   2963     return p;
   2964 }
   2965 
   2966 /* dependency	-> target... op [source...]
   2967  * op		-> ':' | '::' | '!' */
   2968 static void
   2969 ParseDependency(char *line)
   2970 {
   2971     VarEvalFlags eflags;
   2972     char *expanded_line;
   2973     const char *shellcmd = NULL;
   2974 
   2975     /*
   2976      * For some reason - probably to make the parser impossible -
   2977      * a ';' can be used to separate commands from dependencies.
   2978      * Attempt to avoid ';' inside substitution patterns.
   2979      */
   2980     {
   2981         char *semicolon = FindSemicolon(line);
   2982 	if (*semicolon != '\0') {
   2983 	    /* Terminate the dependency list at the ';' */
   2984 	    *semicolon = '\0';
   2985 	    shellcmd = semicolon + 1;
   2986 	}
   2987     }
   2988 
   2989     /*
   2990      * We now know it's a dependency line so it needs to have all
   2991      * variables expanded before being parsed.
   2992      *
   2993      * XXX: Ideally the dependency line would first be split into
   2994      * its left-hand side, dependency operator and right-hand side,
   2995      * and then each side would be expanded on its own.  This would
   2996      * allow for the left-hand side to allow only defined variables
   2997      * and to allow variables on the right-hand side to be undefined
   2998      * as well.
   2999      *
   3000      * Parsing the line first would also prevent that targets
   3001      * generated from variable expressions are interpreted as the
   3002      * dependency operator, such as in "target${:U:} middle: source",
   3003      * in which the middle is interpreted as a source, not a target.
   3004      */
   3005 
   3006     /* In lint mode, allow undefined variables to appear in
   3007      * dependency lines.
   3008      *
   3009      * Ideally, only the right-hand side would allow undefined
   3010      * variables since it is common to have no dependencies.
   3011      * Having undefined variables on the left-hand side is more
   3012      * unusual though.  Since both sides are expanded in a single
   3013      * pass, there is not much choice what to do here.
   3014      *
   3015      * In normal mode, it does not matter whether undefined
   3016      * variables are allowed or not since as of 2020-09-14,
   3017      * Var_Parse does not print any parse errors in such a case.
   3018      * It simply returns the special empty string var_Error,
   3019      * which cannot be detected in the result of Var_Subst. */
   3020     eflags = DEBUG(LINT) ? VARE_WANTRES : VARE_UNDEFERR | VARE_WANTRES;
   3021     (void)Var_Subst(line, VAR_CMD, eflags, &expanded_line);
   3022     /* TODO: handle errors */
   3023 
   3024     /* Need a fresh list for the target nodes */
   3025     if (targets != NULL)
   3026 	Lst_Free(targets);
   3027     targets = Lst_Init();
   3028 
   3029     ParseDoDependency(expanded_line);
   3030     free(expanded_line);
   3031 
   3032     if (shellcmd != NULL)
   3033 	ParseLine_ShellCommand(shellcmd);
   3034 }
   3035 
   3036 static void
   3037 ParseLine(char *line)
   3038 {
   3039     if (ParseDirective(line))
   3040 	return;
   3041 
   3042     if (*line == '\t') {
   3043 	ParseLine_ShellCommand(line + 1);
   3044 	return;
   3045     }
   3046 
   3047 #ifdef SYSVINCLUDE
   3048     if (IsSysVInclude(line)) {
   3049 	/*
   3050 	 * It's an S3/S5-style "include".
   3051 	 */
   3052 	ParseTraditionalInclude(line);
   3053 	return;
   3054     }
   3055 #endif
   3056 
   3057 #ifdef GMAKEEXPORT
   3058     if (strncmp(line, "export", 6) == 0 && ch_isspace(line[6]) &&
   3059 	strchr(line, ':') == NULL) {
   3060 	/*
   3061 	 * It's a Gmake "export".
   3062 	 */
   3063 	ParseGmakeExport(line);
   3064 	return;
   3065     }
   3066 #endif
   3067 
   3068     if (ParseVarassign(line))
   3069 	return;
   3070 
   3071     FinishDependencyGroup();
   3072 
   3073     ParseDependency(line);
   3074 }
   3075 
   3076 /* Parse a top-level makefile into its component parts, incorporating them
   3077  * into the global dependency graph.
   3078  *
   3079  * Input:
   3080  *	name		The name of the file being read
   3081  *	fd		The open file to parse; will be closed at the end
   3082  */
   3083 void
   3084 Parse_File(const char *name, int fd)
   3085 {
   3086     char *line;			/* the line we're working on */
   3087     struct loadedfile *lf;
   3088 
   3089     lf = loadfile(name, fd);
   3090 
   3091     assert(targets == NULL);
   3092     fatals = 0;
   3093 
   3094     if (name == NULL)
   3095 	name = "(stdin)";
   3096 
   3097     Parse_SetInput(name, 0, -1, loadedfile_nextbuf, lf);
   3098     curFile->lf = lf;
   3099 
   3100     do {
   3101 	while ((line = ParseReadLine()) != NULL) {
   3102 	    DEBUG2(PARSE, "ParseReadLine (%d): '%s'\n", curFile->lineno, line);
   3103 	    ParseLine(line);
   3104 	}
   3105 	/*
   3106 	 * Reached EOF, but it may be just EOF of an include file...
   3107 	 */
   3108     } while (ParseEOF());
   3109 
   3110     FinishDependencyGroup();
   3111 
   3112     if (fatals) {
   3113 	(void)fflush(stdout);
   3114 	(void)fprintf(stderr,
   3115 		      "%s: Fatal errors encountered -- cannot continue",
   3116 		      progname);
   3117 	PrintOnError(NULL, NULL);
   3118 	exit(1);
   3119     }
   3120 }
   3121 
   3122 /* Initialize the parsing module. */
   3123 void
   3124 Parse_Init(void)
   3125 {
   3126     mainNode = NULL;
   3127     parseIncPath = Lst_Init();
   3128     sysIncPath = Lst_Init();
   3129     defIncPath = Lst_Init();
   3130     Stack_Init(&includes);
   3131 #ifdef CLEANUP
   3132     targCmds = Lst_Init();
   3133 #endif
   3134 }
   3135 
   3136 /* Clean up the parsing module. */
   3137 void
   3138 Parse_End(void)
   3139 {
   3140 #ifdef CLEANUP
   3141     Lst_Destroy(targCmds, free);
   3142     assert(targets == NULL);
   3143     Lst_Destroy(defIncPath, Dir_Destroy);
   3144     Lst_Destroy(sysIncPath, Dir_Destroy);
   3145     Lst_Destroy(parseIncPath, Dir_Destroy);
   3146     assert(Stack_IsEmpty(&includes));
   3147     Stack_Done(&includes);
   3148 #endif
   3149 }
   3150 
   3151 
   3152 /*-
   3153  *-----------------------------------------------------------------------
   3154  * Parse_MainName --
   3155  *	Return a Lst of the main target to create for main()'s sake. If
   3156  *	no such target exists, we Punt with an obnoxious error message.
   3157  *
   3158  * Results:
   3159  *	A Lst of the single node to create.
   3160  *
   3161  * Side Effects:
   3162  *	None.
   3163  *
   3164  *-----------------------------------------------------------------------
   3165  */
   3166 GNodeList *
   3167 Parse_MainName(void)
   3168 {
   3169     GNodeList *mainList;
   3170 
   3171     mainList = Lst_Init();
   3172 
   3173     if (mainNode == NULL) {
   3174 	Punt("no target to make.");
   3175 	/*NOTREACHED*/
   3176     } else if (mainNode->type & OP_DOUBLEDEP) {
   3177 	Lst_Append(mainList, mainNode);
   3178 	Lst_AppendAll(mainList, mainNode->cohorts);
   3179     } else
   3180 	Lst_Append(mainList, mainNode);
   3181     Var_Append(".TARGETS", mainNode->name, VAR_GLOBAL);
   3182     return mainList;
   3183 }
   3184