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