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