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