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