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