xref: /freebsd/contrib/bmake/parse.c (revision 1edb7116)
1 /*	$NetBSD: parse.c,v 1.716 2024/01/07 11:39:04 rillig Exp $	*/
2 
3 /*
4  * Copyright (c) 1988, 1989, 1990, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Adam de Boor.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 /*
36  * Copyright (c) 1989 by Berkeley Softworks
37  * All rights reserved.
38  *
39  * This code is derived from software contributed to Berkeley by
40  * Adam de Boor.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  * 3. All advertising materials mentioning features or use of this software
51  *    must display the following acknowledgement:
52  *	This product includes software developed by the University of
53  *	California, Berkeley and its contributors.
54  * 4. Neither the name of the University nor the names of its contributors
55  *    may be used to endorse or promote products derived from this software
56  *    without specific prior written permission.
57  *
58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68  * SUCH DAMAGE.
69  */
70 
71 /*
72  * Parsing of makefiles.
73  *
74  * Parse_File is the main entry point and controls most of the other
75  * functions in this module.
76  *
77  * Interface:
78  *	Parse_Init	Initialize the module
79  *
80  *	Parse_End	Clean up the module
81  *
82  *	Parse_File	Parse a top-level makefile.  Included files are
83  *			handled by IncludeFile instead.
84  *
85  *	Parse_VarAssign
86  *			Try to parse the given line as a variable assignment.
87  *			Used by MainParseArgs to determine if an argument is
88  *			a target or a variable assignment.  Used internally
89  *			for pretty much the same thing.
90  *
91  *	Parse_Error	Report a parse error, a warning or an informational
92  *			message.
93  *
94  *	Parse_MainName	Populate the list of targets to create.
95  */
96 
97 #include <sys/types.h>
98 #include <sys/stat.h>
99 #include <errno.h>
100 #include <stdarg.h>
101 
102 #include "make.h"
103 
104 #ifdef HAVE_STDINT_H
105 #include <stdint.h>
106 #endif
107 
108 #ifdef HAVE_MMAP
109 #include <sys/mman.h>
110 
111 #ifndef MAP_COPY
112 #define MAP_COPY MAP_PRIVATE
113 #endif
114 #ifndef MAP_FILE
115 #define MAP_FILE 0
116 #endif
117 #endif
118 
119 #include "dir.h"
120 #include "job.h"
121 #include "pathnames.h"
122 
123 /*	"@(#)parse.c	8.3 (Berkeley) 3/19/94"	*/
124 MAKE_RCSID("$NetBSD: parse.c,v 1.716 2024/01/07 11:39:04 rillig Exp $");
125 
126 /* Detects a multiple-inclusion guard in a makefile. */
127 typedef enum {
128 	GS_START,		/* at the beginning of the file */
129 	GS_COND,		/* after the guard condition */
130 	GS_DONE,		/* after the closing .endif */
131 	GS_NO			/* the file is not guarded */
132 } GuardState;
133 
134 /* A file being parsed. */
135 typedef struct IncludedFile {
136 	FStr name;		/* absolute or relative to the cwd */
137 	unsigned lineno;	/* 1-based */
138 	unsigned readLines;	/* the number of physical lines that have
139 				 * been read from the file */
140 	unsigned forHeadLineno;	/* 1-based */
141 	unsigned forBodyReadLines; /* the number of physical lines that have
142 				 * been read from the file above the body of
143 				 * the .for loop */
144 	unsigned int condMinDepth; /* depth of nested 'if' directives, at the
145 				 * beginning of the file */
146 	bool depending;		/* state of doing_depend on EOF */
147 
148 	Buffer buf;		/* the file's content or the body of the .for
149 				 * loop; either empty or ends with '\n' */
150 	char *buf_ptr;		/* next char to be read from buf */
151 	char *buf_end;		/* buf_end[-1] == '\n' */
152 
153 	GuardState guardState;
154 	Guard *guard;
155 
156 	struct ForLoop *forLoop;
157 } IncludedFile;
158 
159 /* Special attributes for target nodes. */
160 typedef enum ParseSpecial {
161 	SP_ATTRIBUTE,	/* Generic attribute */
162 	SP_BEGIN,	/* .BEGIN */
163 	SP_DEFAULT,	/* .DEFAULT */
164 	SP_DELETE_ON_ERROR, /* .DELETE_ON_ERROR */
165 	SP_END,		/* .END */
166 	SP_ERROR,	/* .ERROR */
167 	SP_IGNORE,	/* .IGNORE */
168 	SP_INCLUDES,	/* .INCLUDES; not mentioned in the manual page */
169 	SP_INTERRUPT,	/* .INTERRUPT */
170 	SP_LIBS,	/* .LIBS; not mentioned in the manual page */
171 	SP_MAIN,	/* .MAIN and no user-specified targets to make */
172 	SP_META,	/* .META */
173 	SP_MFLAGS,	/* .MFLAGS or .MAKEFLAGS */
174 	SP_NOMETA,	/* .NOMETA */
175 	SP_NOMETA_CMP,	/* .NOMETA_CMP */
176 	SP_NOPATH,	/* .NOPATH */
177 	SP_NOREADONLY,	/* .NOREADONLY */
178 	SP_NOT,		/* Not special */
179 	SP_NOTPARALLEL,	/* .NOTPARALLEL or .NO_PARALLEL */
180 	SP_NULL,	/* .NULL; not mentioned in the manual page */
181 	SP_OBJDIR,	/* .OBJDIR */
182 	SP_ORDER,	/* .ORDER */
183 	SP_PARALLEL,	/* .PARALLEL; not mentioned in the manual page */
184 	SP_PATH,	/* .PATH or .PATH.suffix */
185 	SP_PHONY,	/* .PHONY */
186 #ifdef POSIX
187 	SP_POSIX,	/* .POSIX; not mentioned in the manual page */
188 #endif
189 	SP_PRECIOUS,	/* .PRECIOUS */
190 	SP_READONLY,	/* .READONLY */
191 	SP_SHELL,	/* .SHELL */
192 	SP_SILENT,	/* .SILENT */
193 	SP_SINGLESHELL,	/* .SINGLESHELL; not mentioned in the manual page */
194 	SP_STALE,	/* .STALE */
195 	SP_SUFFIXES,	/* .SUFFIXES */
196 	SP_SYSPATH,	/* .SYSPATH */
197 	SP_WAIT		/* .WAIT */
198 } ParseSpecial;
199 
200 typedef List SearchPathList;
201 typedef ListNode SearchPathListNode;
202 
203 
204 typedef enum VarAssignOp {
205 	VAR_NORMAL,		/* = */
206 	VAR_APPEND,		/* += */
207 	VAR_DEFAULT,		/* ?= */
208 	VAR_SUBST,		/* := */
209 	VAR_SHELL		/* != or :sh= */
210 } VarAssignOp;
211 
212 typedef struct VarAssign {
213 	char *varname;		/* unexpanded */
214 	VarAssignOp op;
215 	const char *value;	/* unexpanded */
216 } VarAssign;
217 
218 static bool Parse_IsVar(const char *, VarAssign *);
219 static void Parse_Var(VarAssign *, GNode *);
220 
221 /*
222  * The target to be made if no targets are specified in the command line.
223  * This is the first target defined in any of the makefiles.
224  */
225 GNode *mainNode;
226 
227 /*
228  * During parsing, the targets from the left-hand side of the currently
229  * active dependency line, or NULL if the current line does not belong to a
230  * dependency line, for example because it is a variable assignment.
231  *
232  * See unit-tests/deptgt.mk, keyword "parse.c:targets".
233  */
234 static GNodeList *targets;
235 
236 #ifdef CLEANUP
237 /*
238  * All shell commands for all targets, in no particular order and possibly
239  * with duplicates.  Kept in a separate list since the commands from .USE or
240  * .USEBEFORE nodes are shared with other GNodes, thereby giving up the
241  * easily understandable ownership over the allocated strings.
242  */
243 static StringList targCmds = LST_INIT;
244 #endif
245 
246 /*
247  * Predecessor node for handling .ORDER. Initialized to NULL when .ORDER
248  * is seen, then set to each successive source on the line.
249  */
250 static GNode *order_pred;
251 
252 static int parseErrors;
253 
254 /*
255  * The include chain of makefiles.  At index 0 is the top-level makefile from
256  * the command line, followed by the included files or .for loops, up to and
257  * including the current file.
258  *
259  * See PrintStackTrace for how to interpret the data.
260  */
261 static Vector /* of IncludedFile */ includes;
262 
263 SearchPath *parseIncPath;	/* directories for "..." includes */
264 SearchPath *sysIncPath;		/* directories for <...> includes */
265 SearchPath *defSysIncPath;	/* default for sysIncPath */
266 
267 /*
268  * The parseKeywords table is searched using binary search when deciding
269  * if a target or source is special.
270  */
271 static const struct {
272 	const char name[17];
273 	ParseSpecial special;	/* when used as a target */
274 	GNodeType targetAttr;	/* when used as a source */
275 } parseKeywords[] = {
276     { ".BEGIN",		SP_BEGIN,	OP_NONE },
277     { ".DEFAULT",	SP_DEFAULT,	OP_NONE },
278     { ".DELETE_ON_ERROR", SP_DELETE_ON_ERROR, OP_NONE },
279     { ".END",		SP_END,		OP_NONE },
280     { ".ERROR",		SP_ERROR,	OP_NONE },
281     { ".EXEC",		SP_ATTRIBUTE,	OP_EXEC },
282     { ".IGNORE",	SP_IGNORE,	OP_IGNORE },
283     { ".INCLUDES",	SP_INCLUDES,	OP_NONE },
284     { ".INTERRUPT",	SP_INTERRUPT,	OP_NONE },
285     { ".INVISIBLE",	SP_ATTRIBUTE,	OP_INVISIBLE },
286     { ".JOIN",		SP_ATTRIBUTE,	OP_JOIN },
287     { ".LIBS",		SP_LIBS,	OP_NONE },
288     { ".MADE",		SP_ATTRIBUTE,	OP_MADE },
289     { ".MAIN",		SP_MAIN,	OP_NONE },
290     { ".MAKE",		SP_ATTRIBUTE,	OP_MAKE },
291     { ".MAKEFLAGS",	SP_MFLAGS,	OP_NONE },
292     { ".META",		SP_META,	OP_META },
293     { ".MFLAGS",	SP_MFLAGS,	OP_NONE },
294     { ".NOMETA",	SP_NOMETA,	OP_NOMETA },
295     { ".NOMETA_CMP",	SP_NOMETA_CMP,	OP_NOMETA_CMP },
296     { ".NOPATH",	SP_NOPATH,	OP_NOPATH },
297     { ".NOREADONLY",	SP_NOREADONLY,	OP_NONE },
298     { ".NOTMAIN",	SP_ATTRIBUTE,	OP_NOTMAIN },
299     { ".NOTPARALLEL",	SP_NOTPARALLEL,	OP_NONE },
300     { ".NO_PARALLEL",	SP_NOTPARALLEL,	OP_NONE },
301     { ".NULL",		SP_NULL,	OP_NONE },
302     { ".OBJDIR",	SP_OBJDIR,	OP_NONE },
303     { ".OPTIONAL",	SP_ATTRIBUTE,	OP_OPTIONAL },
304     { ".ORDER",		SP_ORDER,	OP_NONE },
305     { ".PARALLEL",	SP_PARALLEL,	OP_NONE },
306     { ".PATH",		SP_PATH,	OP_NONE },
307     { ".PHONY",		SP_PHONY,	OP_PHONY },
308 #ifdef POSIX
309     { ".POSIX",		SP_POSIX,	OP_NONE },
310 #endif
311     { ".PRECIOUS",	SP_PRECIOUS,	OP_PRECIOUS },
312     { ".READONLY",	SP_READONLY,	OP_NONE },
313     { ".RECURSIVE",	SP_ATTRIBUTE,	OP_MAKE },
314     { ".SHELL",		SP_SHELL,	OP_NONE },
315     { ".SILENT",	SP_SILENT,	OP_SILENT },
316     { ".SINGLESHELL",	SP_SINGLESHELL,	OP_NONE },
317     { ".STALE",		SP_STALE,	OP_NONE },
318     { ".SUFFIXES",	SP_SUFFIXES,	OP_NONE },
319     { ".SYSPATH",	SP_SYSPATH,	OP_NONE },
320     { ".USE",		SP_ATTRIBUTE,	OP_USE },
321     { ".USEBEFORE",	SP_ATTRIBUTE,	OP_USEBEFORE },
322     { ".WAIT",		SP_WAIT,	OP_NONE },
323 };
324 
325 enum PosixState posix_state = PS_NOT_YET;
326 
327 static HashTable /* full file name -> Guard */ guards;
328 
329 
330 static List *
331 Lst_New(void)
332 {
333 	List *list = bmake_malloc(sizeof *list);
334 	Lst_Init(list);
335 	return list;
336 }
337 
338 static void
339 Lst_Free(List *list)
340 {
341 
342 	Lst_Done(list);
343 	free(list);
344 }
345 
346 static IncludedFile *
347 GetInclude(size_t i)
348 {
349 	assert(i < includes.len);
350 	return Vector_Get(&includes, i);
351 }
352 
353 /* The makefile or the body of a .for loop that is currently being read. */
354 static IncludedFile *
355 CurFile(void)
356 {
357 	return GetInclude(includes.len - 1);
358 }
359 
360 unsigned int
361 CurFile_CondMinDepth(void)
362 {
363 	return CurFile()->condMinDepth;
364 }
365 
366 static Buffer
367 LoadFile(const char *path, int fd)
368 {
369 	ssize_t n;
370 	Buffer buf;
371 	size_t bufSize;
372 	struct stat st;
373 
374 	bufSize = fstat(fd, &st) == 0 && S_ISREG(st.st_mode) &&
375 		  st.st_size > 0 && st.st_size < 1024 * 1024 * 1024
376 	    ? (size_t)st.st_size : 1024;
377 	Buf_InitSize(&buf, bufSize);
378 
379 	for (;;) {
380 		if (buf.len == buf.cap) {
381 			if (buf.cap >= 512 * 1024 * 1024) {
382 				Error("%s: file too large", path);
383 				exit(2); /* Not 1 so -q can distinguish error */
384 			}
385 			Buf_Expand(&buf);
386 		}
387 		assert(buf.len < buf.cap);
388 		n = read(fd, buf.data + buf.len, buf.cap - buf.len);
389 		if (n < 0) {
390 			Error("%s: read error: %s", path, strerror(errno));
391 			exit(2);	/* Not 1 so -q can distinguish error */
392 		}
393 		if (n == 0)
394 			break;
395 
396 		buf.len += (size_t)n;
397 	}
398 	assert(buf.len <= buf.cap);
399 
400 	if (buf.len > 0 && !Buf_EndsWith(&buf, '\n'))
401 		Buf_AddByte(&buf, '\n');
402 
403 	return buf;		/* may not be null-terminated */
404 }
405 
406 /*
407  * Print the current chain of .include and .for directives.  In Parse_Fatal
408  * or other functions that already print the location, includingInnermost
409  * would be redundant, but in other cases like Error or Fatal it needs to be
410  * included.
411  */
412 void
413 PrintStackTrace(bool includingInnermost)
414 {
415 	const IncludedFile *entries;
416 	size_t i, n;
417 
418 	n = includes.len;
419 	if (n == 0)
420 		return;
421 
422 	entries = GetInclude(0);
423 	if (!includingInnermost && entries[n - 1].forLoop == NULL)
424 		n--;		/* already in the diagnostic */
425 
426 	for (i = n; i-- > 0;) {
427 		const IncludedFile *entry = entries + i;
428 		const char *fname = entry->name.str;
429 		char dirbuf[MAXPATHLEN + 1];
430 
431 		if (fname[0] != '/' && strcmp(fname, "(stdin)") != 0) {
432 			const char *realPath = realpath(fname, dirbuf);
433 			if (realPath != NULL)
434 				fname = realPath;
435 		}
436 
437 		if (entry->forLoop != NULL) {
438 			char *details = ForLoop_Details(entry->forLoop);
439 			debug_printf("\tin .for loop from %s:%u with %s\n",
440 			    fname, entry->forHeadLineno, details);
441 			free(details);
442 		} else if (i + 1 < n && entries[i + 1].forLoop != NULL) {
443 			/* entry->lineno is not a useful line number */
444 		} else
445 			debug_printf("\tin %s:%u\n", fname, entry->lineno);
446 	}
447 }
448 
449 /* Check if the current character is escaped on the current line. */
450 static bool
451 IsEscaped(const char *line, const char *p)
452 {
453 	bool escaped = false;
454 	while (p > line && *--p == '\\')
455 		escaped = !escaped;
456 	return escaped;
457 }
458 
459 /*
460  * Remember the location (filename and lineno) where the last command was
461  * added or where the node was mentioned in a .depend file.
462  */
463 static void
464 RememberLocation(GNode *gn)
465 {
466 	IncludedFile *curFile = CurFile();
467 	gn->fname = Str_Intern(curFile->name.str);
468 	gn->lineno = curFile->lineno;
469 }
470 
471 /*
472  * Look in the table of keywords for one matching the given string.
473  * Return the index of the keyword, or -1 if it isn't there.
474  */
475 static int
476 FindKeyword(const char *str)
477 {
478 	int start = 0;
479 	int end = sizeof parseKeywords / sizeof parseKeywords[0] - 1;
480 
481 	while (start <= end) {
482 		int curr = start + (end - start) / 2;
483 		int diff = strcmp(str, parseKeywords[curr].name);
484 
485 		if (diff == 0)
486 			return curr;
487 		if (diff < 0)
488 			end = curr - 1;
489 		else
490 			start = curr + 1;
491 	}
492 
493 	return -1;
494 }
495 
496 void
497 PrintLocation(FILE *f, bool useVars, const GNode *gn)
498 {
499 	char dirbuf[MAXPATHLEN + 1];
500 	FStr dir, base;
501 	const char *fname;
502 	unsigned lineno;
503 
504 	if (gn != NULL) {
505 		fname = gn->fname;
506 		lineno = gn->lineno;
507 	} else if (includes.len > 0) {
508 		IncludedFile *curFile = CurFile();
509 		fname = curFile->name.str;
510 		lineno = curFile->lineno;
511 	} else
512 		return;
513 
514 	if (!useVars || fname[0] == '/' || strcmp(fname, "(stdin)") == 0) {
515 		(void)fprintf(f, "\"%s\" line %u: ", fname, lineno);
516 		return;
517 	}
518 
519 	dir = Var_Value(SCOPE_GLOBAL, ".PARSEDIR");
520 	if (dir.str == NULL)
521 		dir.str = ".";
522 	if (dir.str[0] != '/')
523 		dir.str = realpath(dir.str, dirbuf);
524 
525 	base = Var_Value(SCOPE_GLOBAL, ".PARSEFILE");
526 	if (base.str == NULL)
527 		base.str = str_basename(fname);
528 
529 	(void)fprintf(f, "\"%s/%s\" line %u: ", dir.str, base.str, lineno);
530 
531 	FStr_Done(&base);
532 	FStr_Done(&dir);
533 }
534 
535 static void MAKE_ATTR_PRINTFLIKE(5, 0)
536 ParseVErrorInternal(FILE *f, bool useVars, const GNode *gn,
537 		    ParseErrorLevel level, const char *fmt, va_list ap)
538 {
539 	static bool fatal_warning_error_printed = false;
540 
541 	(void)fprintf(f, "%s: ", progname);
542 
543 	PrintLocation(f, useVars, gn);
544 	if (level == PARSE_WARNING)
545 		(void)fprintf(f, "warning: ");
546 	(void)vfprintf(f, fmt, ap);
547 	(void)fprintf(f, "\n");
548 	(void)fflush(f);
549 
550 	if (level == PARSE_FATAL)
551 		parseErrors++;
552 	if (level == PARSE_WARNING && opts.parseWarnFatal) {
553 		if (!fatal_warning_error_printed) {
554 			Error("parsing warnings being treated as errors");
555 			fatal_warning_error_printed = true;
556 		}
557 		parseErrors++;
558 	}
559 
560 	if (DEBUG(PARSE))
561 		PrintStackTrace(false);
562 }
563 
564 static void MAKE_ATTR_PRINTFLIKE(3, 4)
565 ParseErrorInternal(const GNode *gn,
566 		   ParseErrorLevel level, const char *fmt, ...)
567 {
568 	va_list ap;
569 
570 	(void)fflush(stdout);
571 	va_start(ap, fmt);
572 	ParseVErrorInternal(stderr, false, gn, level, fmt, ap);
573 	va_end(ap);
574 
575 	if (opts.debug_file != stdout && opts.debug_file != stderr) {
576 		va_start(ap, fmt);
577 		ParseVErrorInternal(opts.debug_file, false, gn,
578 		    level, fmt, ap);
579 		va_end(ap);
580 	}
581 }
582 
583 /*
584  * Print a message, including location information.
585  *
586  * If the level is PARSE_FATAL, continue parsing until the end of the
587  * current top-level makefile, then exit (see Parse_File).
588  *
589  * Fmt is given without a trailing newline.
590  */
591 void
592 Parse_Error(ParseErrorLevel level, const char *fmt, ...)
593 {
594 	va_list ap;
595 
596 	(void)fflush(stdout);
597 	va_start(ap, fmt);
598 	ParseVErrorInternal(stderr, true, NULL, level, fmt, ap);
599 	va_end(ap);
600 
601 	if (opts.debug_file != stdout && opts.debug_file != stderr) {
602 		va_start(ap, fmt);
603 		ParseVErrorInternal(opts.debug_file, true, NULL,
604 		    level, fmt, ap);
605 		va_end(ap);
606 	}
607 }
608 
609 
610 /*
611  * Handle an .info, .warning or .error directive.  For an .error directive,
612  * exit immediately.
613  */
614 static void
615 HandleMessage(ParseErrorLevel level, const char *levelName, const char *umsg)
616 {
617 	char *xmsg;
618 
619 	if (umsg[0] == '\0') {
620 		Parse_Error(PARSE_FATAL, "Missing argument for \".%s\"",
621 		    levelName);
622 		return;
623 	}
624 
625 	xmsg = Var_Subst(umsg, SCOPE_CMDLINE, VARE_WANTRES);
626 	/* TODO: handle errors */
627 
628 	Parse_Error(level, "%s", xmsg);
629 	free(xmsg);
630 
631 	if (level == PARSE_FATAL) {
632 		PrintOnError(NULL, "\n");
633 		exit(1);
634 	}
635 }
636 
637 /*
638  * Add the child to the parent's children, and for non-special targets, vice
639  * versa.
640  */
641 static void
642 LinkSource(GNode *pgn, GNode *cgn, bool isSpecial)
643 {
644 	if ((pgn->type & OP_DOUBLEDEP) && !Lst_IsEmpty(&pgn->cohorts))
645 		pgn = pgn->cohorts.last->datum;
646 
647 	Lst_Append(&pgn->children, cgn);
648 	pgn->unmade++;
649 
650 	/*
651 	 * Special targets like .END do not need to be informed once the child
652 	 * target has been made.
653 	 */
654 	if (!isSpecial)
655 		Lst_Append(&cgn->parents, pgn);
656 
657 	if (DEBUG(PARSE)) {
658 		debug_printf("# LinkSource: added child %s - %s\n",
659 		    pgn->name, cgn->name);
660 		Targ_PrintNode(pgn, 0);
661 		Targ_PrintNode(cgn, 0);
662 	}
663 }
664 
665 /* Add the node to each target from the current dependency group. */
666 static void
667 LinkToTargets(GNode *gn, bool isSpecial)
668 {
669 	GNodeListNode *ln;
670 
671 	for (ln = targets->first; ln != NULL; ln = ln->next)
672 		LinkSource(ln->datum, gn, isSpecial);
673 }
674 
675 static bool
676 TryApplyDependencyOperator(GNode *gn, GNodeType op)
677 {
678 	/*
679 	 * If the node occurred on the left-hand side of a dependency and the
680 	 * operator also defines a dependency, they must match.
681 	 */
682 	if ((op & OP_OPMASK) && (gn->type & OP_OPMASK) &&
683 	    ((op & OP_OPMASK) != (gn->type & OP_OPMASK))) {
684 		Parse_Error(PARSE_FATAL, "Inconsistent operator for %s",
685 		    gn->name);
686 		return false;
687 	}
688 
689 	if (op == OP_DOUBLEDEP && (gn->type & OP_OPMASK) == OP_DOUBLEDEP) {
690 		/*
691 		 * If the node was on the left-hand side of a '::' operator,
692 		 * create a new node for the children and commands on this
693 		 * dependency line, since each of these dependency groups has
694 		 * its own attributes and commands, separate from the others.
695 		 *
696 		 * The new instance is placed on the 'cohorts' list of the
697 		 * initial one (note the initial one is not on its own
698 		 * cohorts list) and the new instance is linked to all
699 		 * parents of the initial instance.
700 		 */
701 		GNode *cohort;
702 
703 		/*
704 		 * Propagate copied bits to the initial node.  They'll be
705 		 * propagated back to the rest of the cohorts later.
706 		 */
707 		gn->type |= op & (unsigned)~OP_OPMASK;
708 
709 		cohort = Targ_NewInternalNode(gn->name);
710 		if (doing_depend)
711 			RememberLocation(cohort);
712 		/*
713 		 * Make the cohort invisible to avoid duplicating it
714 		 * into other variables. True, parents of this target won't
715 		 * tend to do anything with their local variables, but better
716 		 * safe than sorry.
717 		 *
718 		 * (I think this is pointless now, since the relevant list
719 		 * traversals will no longer see this node anyway. -mycroft)
720 		 */
721 		cohort->type = op | OP_INVISIBLE;
722 		Lst_Append(&gn->cohorts, cohort);
723 		cohort->centurion = gn;
724 		gn->unmade_cohorts++;
725 		snprintf(cohort->cohort_num, sizeof cohort->cohort_num, "#%d",
726 		    (unsigned int)gn->unmade_cohorts % 1000000);
727 	} else {
728 		gn->type |= op;	/* preserve any previous flags */
729 	}
730 
731 	return true;
732 }
733 
734 static void
735 ApplyDependencyOperator(GNodeType op)
736 {
737 	GNodeListNode *ln;
738 
739 	for (ln = targets->first; ln != NULL; ln = ln->next)
740 		if (!TryApplyDependencyOperator(ln->datum, op))
741 			break;
742 }
743 
744 /*
745  * Add a .WAIT node in the dependency list. After any dynamic dependencies
746  * (and filename globbing) have happened, it is given a dependency on each
747  * previous child, back until the previous .WAIT node. The next child won't
748  * be scheduled until the .WAIT node is built.
749  *
750  * Give each .WAIT node a unique name (mainly for diagnostics).
751  */
752 static void
753 ApplyDependencySourceWait(bool isSpecial)
754 {
755 	static unsigned wait_number = 0;
756 	char name[6 + 10 + 1];
757 	GNode *gn;
758 
759 	snprintf(name, sizeof name, ".WAIT_%u", ++wait_number);
760 	gn = Targ_NewInternalNode(name);
761 	if (doing_depend)
762 		RememberLocation(gn);
763 	gn->type = OP_WAIT | OP_PHONY | OP_DEPENDS | OP_NOTMAIN;
764 	LinkToTargets(gn, isSpecial);
765 }
766 
767 static bool
768 ApplyDependencySourceKeyword(const char *src, ParseSpecial special)
769 {
770 	int keywd;
771 	GNodeType targetAttr;
772 
773 	if (*src != '.' || !ch_isupper(src[1]))
774 		return false;
775 
776 	keywd = FindKeyword(src);
777 	if (keywd == -1)
778 		return false;
779 
780 	targetAttr = parseKeywords[keywd].targetAttr;
781 	if (targetAttr != OP_NONE) {
782 		ApplyDependencyOperator(targetAttr);
783 		return true;
784 	}
785 	if (parseKeywords[keywd].special == SP_WAIT) {
786 		ApplyDependencySourceWait(special != SP_NOT);
787 		return true;
788 	}
789 	return false;
790 }
791 
792 /*
793  * In a line like ".MAIN: source1 source2", add all sources to the list of
794  * things to create, but only if the user didn't specify a target on the
795  * command line and .MAIN occurs for the first time.
796  *
797  * See HandleDependencyTargetSpecial, branch SP_MAIN.
798  * See unit-tests/cond-func-make-main.mk.
799  */
800 static void
801 ApplyDependencySourceMain(const char *src)
802 {
803 	Lst_Append(&opts.create, bmake_strdup(src));
804 	/*
805 	 * Add the name to the .TARGETS variable as well, so the user can
806 	 * employ that, if desired.
807 	 */
808 	Global_Append(".TARGETS", src);
809 }
810 
811 /*
812  * For the sources of a .ORDER target, create predecessor/successor links
813  * between the previous source and the current one.
814  */
815 static void
816 ApplyDependencySourceOrder(const char *src)
817 {
818 	GNode *gn;
819 
820 	gn = Targ_GetNode(src);
821 	if (doing_depend)
822 		RememberLocation(gn);
823 	if (order_pred != NULL) {
824 		Lst_Append(&order_pred->order_succ, gn);
825 		Lst_Append(&gn->order_pred, order_pred);
826 		if (DEBUG(PARSE)) {
827 			debug_printf(
828 			    "# .ORDER forces '%s' to be made before '%s'\n",
829 			    order_pred->name, gn->name);
830 			Targ_PrintNode(order_pred, 0);
831 			Targ_PrintNode(gn, 0);
832 		}
833 	}
834 	/* The current source now becomes the predecessor for the next one. */
835 	order_pred = gn;
836 }
837 
838 /* The source is not an attribute, so find/create a node for it. */
839 static void
840 ApplyDependencySourceOther(const char *src, GNodeType targetAttr,
841 			   ParseSpecial special)
842 {
843 	GNode *gn;
844 
845 	gn = Targ_GetNode(src);
846 	if (doing_depend)
847 		RememberLocation(gn);
848 	if (targetAttr != OP_NONE)
849 		gn->type |= targetAttr;
850 	else
851 		LinkToTargets(gn, special != SP_NOT);
852 }
853 
854 /*
855  * Given the name of a source in a dependency line, figure out if it is an
856  * attribute (such as .SILENT) and if so, apply it to all targets. Otherwise
857  * decide if there is some attribute which should be applied *to* the source
858  * because of some special target (such as .PHONY) and apply it if so.
859  * Otherwise, make the source a child of the targets.
860  */
861 static void
862 ApplyDependencySource(GNodeType targetAttr, const char *src,
863 		      ParseSpecial special)
864 {
865 	if (ApplyDependencySourceKeyword(src, special))
866 		return;
867 
868 	if (special == SP_MAIN)
869 		ApplyDependencySourceMain(src);
870 	else if (special == SP_ORDER)
871 		ApplyDependencySourceOrder(src);
872 	else
873 		ApplyDependencySourceOther(src, targetAttr, special);
874 }
875 
876 /*
877  * If we have yet to decide on a main target to make, in the absence of any
878  * user input, we want the first target on the first dependency line that is
879  * actually a real target (i.e. isn't a .USE or .EXEC rule) to be made.
880  */
881 static void
882 MaybeUpdateMainTarget(void)
883 {
884 	GNodeListNode *ln;
885 
886 	if (mainNode != NULL)
887 		return;
888 
889 	for (ln = targets->first; ln != NULL; ln = ln->next) {
890 		GNode *gn = ln->datum;
891 		if (GNode_IsMainCandidate(gn)) {
892 			DEBUG1(MAKE, "Setting main node to \"%s\"\n",
893 			    gn->name);
894 			mainNode = gn;
895 			return;
896 		}
897 	}
898 }
899 
900 static void
901 InvalidLineType(const char *line, const char *unexpanded_line)
902 {
903 	if (unexpanded_line[0] == '.') {
904 		const char *dirstart = unexpanded_line + 1;
905 		const char *dirend;
906 		cpp_skip_whitespace(&dirstart);
907 		dirend = dirstart;
908 		while (ch_isalnum(*dirend) || *dirend == '-')
909 			dirend++;
910 		Parse_Error(PARSE_FATAL, "Unknown directive \"%.*s\"",
911 		    (int)(dirend - dirstart), dirstart);
912 	} else if (strcmp(line, unexpanded_line) == 0)
913 		Parse_Error(PARSE_FATAL, "Invalid line '%s'", line);
914 	else
915 		Parse_Error(PARSE_FATAL,
916 		    "Invalid line '%s', expanded to '%s'",
917 		    unexpanded_line, line);
918 }
919 
920 static void
921 ParseDependencyTargetWord(char **pp, const char *lstart)
922 {
923 	const char *p = *pp;
924 
925 	while (*p != '\0') {
926 		if ((ch_isspace(*p) || *p == '!' || *p == ':' || *p == '(')
927 		    && !IsEscaped(lstart, p))
928 			break;
929 
930 		if (*p == '$') {
931 			FStr val = Var_Parse(&p, SCOPE_CMDLINE,
932 			    VARE_PARSE_ONLY);
933 			/* TODO: handle errors */
934 			FStr_Done(&val);
935 		} else
936 			p++;
937 	}
938 
939 	*pp += p - *pp;
940 }
941 
942 /*
943  * Handle special targets like .PATH, .DEFAULT, .BEGIN, .ORDER.
944  *
945  * See the tests deptgt-*.mk.
946  */
947 static void
948 HandleDependencyTargetSpecial(const char *targetName,
949 			      ParseSpecial *inout_special,
950 			      SearchPathList **inout_paths)
951 {
952 	switch (*inout_special) {
953 	case SP_PATH:
954 		if (*inout_paths == NULL)
955 			*inout_paths = Lst_New();
956 		Lst_Append(*inout_paths, &dirSearchPath);
957 		break;
958 	case SP_SYSPATH:
959 		if (*inout_paths == NULL)
960 			*inout_paths = Lst_New();
961 		Lst_Append(*inout_paths, sysIncPath);
962 		break;
963 	case SP_MAIN:
964 		/*
965 		 * Allow targets from the command line to override the
966 		 * .MAIN node.
967 		 */
968 		if (!Lst_IsEmpty(&opts.create))
969 			*inout_special = SP_NOT;
970 		break;
971 	case SP_BEGIN:
972 	case SP_END:
973 	case SP_STALE:
974 	case SP_ERROR:
975 	case SP_INTERRUPT: {
976 		GNode *gn = Targ_GetNode(targetName);
977 		if (doing_depend)
978 			RememberLocation(gn);
979 		gn->type |= OP_NOTMAIN | OP_SPECIAL;
980 		Lst_Append(targets, gn);
981 		break;
982 	}
983 	case SP_DEFAULT: {
984 		/*
985 		 * Need to create a node to hang commands on, but we don't
986 		 * want it in the graph, nor do we want it to be the Main
987 		 * Target. We claim the node is a transformation rule to make
988 		 * life easier later, when we'll use Make_HandleUse to
989 		 * actually apply the .DEFAULT commands.
990 		 */
991 		GNode *gn = GNode_New(".DEFAULT");
992 		gn->type |= OP_NOTMAIN | OP_TRANSFORM;
993 		Lst_Append(targets, gn);
994 		defaultNode = gn;
995 		break;
996 	}
997 	case SP_DELETE_ON_ERROR:
998 		deleteOnError = true;
999 		break;
1000 	case SP_NOTPARALLEL:
1001 		opts.maxJobs = 1;
1002 		break;
1003 	case SP_SINGLESHELL:
1004 		opts.compatMake = true;
1005 		break;
1006 	case SP_ORDER:
1007 		order_pred = NULL;
1008 		break;
1009 	default:
1010 		break;
1011 	}
1012 }
1013 
1014 static bool
1015 HandleDependencyTargetPath(const char *suffixName,
1016 			   SearchPathList **inout_paths)
1017 {
1018 	SearchPath *path;
1019 
1020 	path = Suff_GetPath(suffixName);
1021 	if (path == NULL) {
1022 		Parse_Error(PARSE_FATAL,
1023 		    "Suffix '%s' not defined (yet)", suffixName);
1024 		return false;
1025 	}
1026 
1027 	if (*inout_paths == NULL)
1028 		*inout_paths = Lst_New();
1029 	Lst_Append(*inout_paths, path);
1030 
1031 	return true;
1032 }
1033 
1034 /* See if it's a special target and if so set inout_special to match it. */
1035 static bool
1036 HandleDependencyTarget(const char *targetName,
1037 		       ParseSpecial *inout_special,
1038 		       GNodeType *inout_targetAttr,
1039 		       SearchPathList **inout_paths)
1040 {
1041 	int keywd;
1042 
1043 	if (!(targetName[0] == '.' && ch_isupper(targetName[1])))
1044 		return true;
1045 
1046 	/*
1047 	 * See if the target is a special target that must have it
1048 	 * or its sources handled specially.
1049 	 */
1050 	keywd = FindKeyword(targetName);
1051 	if (keywd != -1) {
1052 		if (*inout_special == SP_PATH &&
1053 		    parseKeywords[keywd].special != SP_PATH) {
1054 			Parse_Error(PARSE_FATAL, "Mismatched special targets");
1055 			return false;
1056 		}
1057 
1058 		*inout_special = parseKeywords[keywd].special;
1059 		*inout_targetAttr = parseKeywords[keywd].targetAttr;
1060 
1061 		HandleDependencyTargetSpecial(targetName, inout_special,
1062 		    inout_paths);
1063 
1064 	} else if (strncmp(targetName, ".PATH", 5) == 0) {
1065 		*inout_special = SP_PATH;
1066 		if (!HandleDependencyTargetPath(targetName + 5, inout_paths))
1067 			return false;
1068 	}
1069 	return true;
1070 }
1071 
1072 static void
1073 HandleSingleDependencyTargetMundane(const char *name)
1074 {
1075 	GNode *gn = Suff_IsTransform(name)
1076 	    ? Suff_AddTransform(name)
1077 	    : Targ_GetNode(name);
1078 	if (doing_depend)
1079 		RememberLocation(gn);
1080 
1081 	Lst_Append(targets, gn);
1082 }
1083 
1084 static void
1085 HandleDependencyTargetMundane(const char *targetName)
1086 {
1087 	if (Dir_HasWildcards(targetName)) {
1088 		StringList targetNames = LST_INIT;
1089 
1090 		SearchPath *emptyPath = SearchPath_New();
1091 		SearchPath_Expand(emptyPath, targetName, &targetNames);
1092 		SearchPath_Free(emptyPath);
1093 
1094 		while (!Lst_IsEmpty(&targetNames)) {
1095 			char *targName = Lst_Dequeue(&targetNames);
1096 			HandleSingleDependencyTargetMundane(targName);
1097 			free(targName);
1098 		}
1099 	} else
1100 		HandleSingleDependencyTargetMundane(targetName);
1101 }
1102 
1103 static void
1104 SkipExtraTargets(char **pp, const char *lstart)
1105 {
1106 	bool warning = false;
1107 	const char *p = *pp;
1108 
1109 	while (*p != '\0') {
1110 		if (!IsEscaped(lstart, p) && (*p == '!' || *p == ':'))
1111 			break;
1112 		if (IsEscaped(lstart, p) || (*p != ' ' && *p != '\t'))
1113 			warning = true;
1114 		p++;
1115 	}
1116 	if (warning) {
1117 		const char *start = *pp;
1118 		cpp_skip_whitespace(&start);
1119 		Parse_Error(PARSE_WARNING, "Extra target '%.*s' ignored",
1120 		    (int)(p - start), start);
1121 	}
1122 
1123 	*pp += p - *pp;
1124 }
1125 
1126 static void
1127 CheckSpecialMundaneMixture(ParseSpecial special)
1128 {
1129 	switch (special) {
1130 	case SP_DEFAULT:
1131 	case SP_STALE:
1132 	case SP_BEGIN:
1133 	case SP_END:
1134 	case SP_ERROR:
1135 	case SP_INTERRUPT:
1136 		/*
1137 		 * These create nodes on which to hang commands, so targets
1138 		 * shouldn't be empty.
1139 		 */
1140 	case SP_NOT:
1141 		/* Nothing special here -- targets may be empty. */
1142 		break;
1143 	default:
1144 		Parse_Error(PARSE_WARNING,
1145 		    "Special and mundane targets don't mix. "
1146 		    "Mundane ones ignored");
1147 		break;
1148 	}
1149 }
1150 
1151 /*
1152  * In a dependency line like 'targets: sources' or 'targets! sources', parse
1153  * the operator ':', '::' or '!' from between the targets and the sources.
1154  */
1155 static GNodeType
1156 ParseDependencyOp(char **pp)
1157 {
1158 	if (**pp == '!')
1159 		return (*pp)++, OP_FORCE;
1160 	if (**pp == ':' && (*pp)[1] == ':')
1161 		return *pp += 2, OP_DOUBLEDEP;
1162 	else if (**pp == ':')
1163 		return (*pp)++, OP_DEPENDS;
1164 	else
1165 		return OP_NONE;
1166 }
1167 
1168 static void
1169 ClearPaths(ParseSpecial special, SearchPathList *paths)
1170 {
1171 	if (paths != NULL) {
1172 		SearchPathListNode *ln;
1173 		for (ln = paths->first; ln != NULL; ln = ln->next)
1174 			SearchPath_Clear(ln->datum);
1175 	}
1176 	if (special == SP_SYSPATH)
1177 		Dir_SetSYSPATH();
1178 	else
1179 		Dir_SetPATH();
1180 }
1181 
1182 static char *
1183 FindInDirOfIncludingFile(const char *file)
1184 {
1185 	char *fullname, *incdir, *slash, *newName;
1186 	int i;
1187 
1188 	fullname = NULL;
1189 	incdir = bmake_strdup(CurFile()->name.str);
1190 	slash = strrchr(incdir, '/');
1191 	if (slash != NULL) {
1192 		*slash = '\0';
1193 		/*
1194 		 * Now do lexical processing of leading "../" on the
1195 		 * filename.
1196 		 */
1197 		for (i = 0; strncmp(file + i, "../", 3) == 0; i += 3) {
1198 			slash = strrchr(incdir + 1, '/');
1199 			if (slash == NULL || strcmp(slash, "/..") == 0)
1200 				break;
1201 			*slash = '\0';
1202 		}
1203 		newName = str_concat3(incdir, "/", file + i);
1204 		fullname = Dir_FindFile(newName, parseIncPath);
1205 		if (fullname == NULL)
1206 			fullname = Dir_FindFile(newName, &dirSearchPath);
1207 		free(newName);
1208 	}
1209 	free(incdir);
1210 	return fullname;
1211 }
1212 
1213 static char *
1214 FindInQuotPath(const char *file)
1215 {
1216 	const char *suff;
1217 	SearchPath *suffPath;
1218 	char *fullname;
1219 
1220 	fullname = FindInDirOfIncludingFile(file);
1221 	if (fullname == NULL &&
1222 	    (suff = strrchr(file, '.')) != NULL &&
1223 	    (suffPath = Suff_GetPath(suff)) != NULL)
1224 		fullname = Dir_FindFile(file, suffPath);
1225 	if (fullname == NULL)
1226 		fullname = Dir_FindFile(file, parseIncPath);
1227 	if (fullname == NULL)
1228 		fullname = Dir_FindFile(file, &dirSearchPath);
1229 	return fullname;
1230 }
1231 
1232 static bool
1233 SkipGuarded(const char *fullname)
1234 {
1235 	Guard *guard = HashTable_FindValue(&guards, fullname);
1236 	if (guard != NULL && guard->kind == GK_VARIABLE
1237 	    && GNode_ValueDirect(SCOPE_GLOBAL, guard->name) != NULL)
1238 		goto skip;
1239 	if (guard != NULL && guard->kind == GK_TARGET
1240 	    && Targ_FindNode(guard->name) != NULL)
1241 		goto skip;
1242 	return false;
1243 
1244 skip:
1245 	DEBUG2(PARSE, "Skipping '%s' because '%s' is defined\n",
1246 	    fullname, guard->name);
1247 	return true;
1248 }
1249 
1250 /*
1251  * Handle one of the .[-ds]include directives by remembering the current file
1252  * and pushing the included file on the stack.  After the included file has
1253  * finished, parsing continues with the including file; see Parse_PushInput
1254  * and ParseEOF.
1255  *
1256  * System includes are looked up in sysIncPath, any other includes are looked
1257  * up in the parsedir and then in the directories specified by the -I command
1258  * line options.
1259  */
1260 static void
1261 IncludeFile(const char *file, bool isSystem, bool depinc, bool silent)
1262 {
1263 	Buffer buf;
1264 	char *fullname;		/* full pathname of file */
1265 	int fd;
1266 
1267 	fullname = file[0] == '/' ? bmake_strdup(file) : NULL;
1268 
1269 	if (fullname == NULL && !isSystem)
1270 		fullname = FindInQuotPath(file);
1271 
1272 	if (fullname == NULL) {
1273 		SearchPath *path = Lst_IsEmpty(&sysIncPath->dirs)
1274 		    ? defSysIncPath : sysIncPath;
1275 		fullname = Dir_FindFile(file, path);
1276 	}
1277 
1278 	if (fullname == NULL) {
1279 		if (!silent)
1280 			Parse_Error(PARSE_FATAL, "Could not find %s", file);
1281 		return;
1282 	}
1283 
1284 	if (SkipGuarded(fullname))
1285 		return;
1286 
1287 	if ((fd = open(fullname, O_RDONLY)) == -1) {
1288 		if (!silent)
1289 			Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
1290 		free(fullname);
1291 		return;
1292 	}
1293 
1294 	buf = LoadFile(fullname, fd);
1295 	(void)close(fd);
1296 
1297 	Parse_PushInput(fullname, 1, 0, buf, NULL);
1298 	if (depinc)
1299 		doing_depend = depinc;	/* only turn it on */
1300 	free(fullname);
1301 }
1302 
1303 /* Handle a "dependency" line like '.SPECIAL:' without any sources. */
1304 static void
1305 HandleDependencySourcesEmpty(ParseSpecial special, SearchPathList *paths)
1306 {
1307 	switch (special) {
1308 	case SP_SUFFIXES:
1309 		Suff_ClearSuffixes();
1310 		break;
1311 	case SP_PRECIOUS:
1312 		allPrecious = true;
1313 		break;
1314 	case SP_IGNORE:
1315 		opts.ignoreErrors = true;
1316 		break;
1317 	case SP_SILENT:
1318 		opts.silent = true;
1319 		break;
1320 	case SP_PATH:
1321 	case SP_SYSPATH:
1322 		ClearPaths(special, paths);
1323 		break;
1324 #ifdef POSIX
1325 	case SP_POSIX:
1326 		if (posix_state == PS_NOW_OR_NEVER) {
1327 			/*
1328 			 * With '-r', 'posix.mk' (if it exists)
1329 			 * can effectively substitute for 'sys.mk',
1330 			 * otherwise it is an extension.
1331 			 */
1332 			Global_Set("%POSIX", "1003.2");
1333 			IncludeFile("posix.mk", true, false, true);
1334 		}
1335 		break;
1336 #endif
1337 	default:
1338 		break;
1339 	}
1340 }
1341 
1342 static void
1343 AddToPaths(const char *dir, SearchPathList *paths)
1344 {
1345 	if (paths != NULL) {
1346 		SearchPathListNode *ln;
1347 		for (ln = paths->first; ln != NULL; ln = ln->next)
1348 			(void)SearchPath_Add(ln->datum, dir);
1349 	}
1350 }
1351 
1352 /*
1353  * If the target was one that doesn't take files as its sources but takes
1354  * something like suffixes, we take each space-separated word on the line as
1355  * a something and deal with it accordingly.
1356  */
1357 static void
1358 ParseDependencySourceSpecial(ParseSpecial special, const char *word,
1359 			     SearchPathList *paths)
1360 {
1361 	switch (special) {
1362 	case SP_SUFFIXES:
1363 		Suff_AddSuffix(word);
1364 		break;
1365 	case SP_PATH:
1366 	case SP_SYSPATH:
1367 		AddToPaths(word, paths);
1368 		break;
1369 	case SP_INCLUDES:
1370 		Suff_AddInclude(word);
1371 		break;
1372 	case SP_LIBS:
1373 		Suff_AddLib(word);
1374 		break;
1375 	case SP_NOREADONLY:
1376 		Var_ReadOnly(word, false);
1377 		break;
1378 	case SP_NULL:
1379 		Suff_SetNull(word);
1380 		break;
1381 	case SP_OBJDIR:
1382 		Main_SetObjdir(false, "%s", word);
1383 		break;
1384 	case SP_READONLY:
1385 		Var_ReadOnly(word, true);
1386 		break;
1387 	default:
1388 		break;
1389 	}
1390 }
1391 
1392 static bool
1393 ApplyDependencyTarget(char *name, char *nameEnd, ParseSpecial *inout_special,
1394 		      GNodeType *inout_targetAttr,
1395 		      SearchPathList **inout_paths)
1396 {
1397 	char savedNameEnd = *nameEnd;
1398 	*nameEnd = '\0';
1399 
1400 	if (!HandleDependencyTarget(name, inout_special,
1401 	    inout_targetAttr, inout_paths))
1402 		return false;
1403 
1404 	if (*inout_special == SP_NOT && *name != '\0')
1405 		HandleDependencyTargetMundane(name);
1406 	else if (*inout_special == SP_PATH && *name != '.' && *name != '\0')
1407 		Parse_Error(PARSE_WARNING, "Extra target (%s) ignored", name);
1408 
1409 	*nameEnd = savedNameEnd;
1410 	return true;
1411 }
1412 
1413 static bool
1414 ParseDependencyTargets(char **pp,
1415 		       const char *lstart,
1416 		       ParseSpecial *inout_special,
1417 		       GNodeType *inout_targetAttr,
1418 		       SearchPathList **inout_paths,
1419 		       const char *unexpanded_line)
1420 {
1421 	char *p = *pp;
1422 
1423 	for (;;) {
1424 		char *tgt = p;
1425 
1426 		ParseDependencyTargetWord(&p, lstart);
1427 
1428 		/*
1429 		 * If the word is followed by a left parenthesis, it's the
1430 		 * name of one or more files inside an archive.
1431 		 */
1432 		if (!IsEscaped(lstart, p) && *p == '(') {
1433 			p = tgt;
1434 			if (!Arch_ParseArchive(&p, targets, SCOPE_CMDLINE)) {
1435 				Parse_Error(PARSE_FATAL,
1436 				    "Error in archive specification: \"%s\"",
1437 				    tgt);
1438 				return false;
1439 			}
1440 			continue;
1441 		}
1442 
1443 		if (*p == '\0') {
1444 			InvalidLineType(lstart, unexpanded_line);
1445 			return false;
1446 		}
1447 
1448 		if (!ApplyDependencyTarget(tgt, p, inout_special,
1449 		    inout_targetAttr, inout_paths))
1450 			return false;
1451 
1452 		if (*inout_special != SP_NOT && *inout_special != SP_PATH)
1453 			SkipExtraTargets(&p, lstart);
1454 		else
1455 			pp_skip_whitespace(&p);
1456 
1457 		if (*p == '\0')
1458 			break;
1459 		if ((*p == '!' || *p == ':') && !IsEscaped(lstart, p))
1460 			break;
1461 	}
1462 
1463 	*pp = p;
1464 	return true;
1465 }
1466 
1467 static void
1468 ParseDependencySourcesSpecial(char *start,
1469 			      ParseSpecial special, SearchPathList *paths)
1470 {
1471 
1472 	while (*start != '\0') {
1473 		char savedEnd;
1474 		char *end = start;
1475 		while (*end != '\0' && !ch_isspace(*end))
1476 			end++;
1477 		savedEnd = *end;
1478 		*end = '\0';
1479 		ParseDependencySourceSpecial(special, start, paths);
1480 		*end = savedEnd;
1481 		if (savedEnd != '\0')
1482 			end++;
1483 		pp_skip_whitespace(&end);
1484 		start = end;
1485 	}
1486 }
1487 
1488 static void
1489 LinkVarToTargets(VarAssign *var)
1490 {
1491 	GNodeListNode *ln;
1492 
1493 	for (ln = targets->first; ln != NULL; ln = ln->next)
1494 		Parse_Var(var, ln->datum);
1495 }
1496 
1497 static bool
1498 ParseDependencySourcesMundane(char *start,
1499 			      ParseSpecial special, GNodeType targetAttr)
1500 {
1501 	while (*start != '\0') {
1502 		char *end = start;
1503 		VarAssign var;
1504 
1505 		/*
1506 		 * Check for local variable assignment,
1507 		 * rest of the line is the value.
1508 		 */
1509 		if (Parse_IsVar(start, &var)) {
1510 			bool targetVarsEnabled = GetBooleanExpr(
1511 			    "${.MAKE.TARGET_LOCAL_VARIABLES}", true);
1512 
1513 			if (targetVarsEnabled)
1514 				LinkVarToTargets(&var);
1515 			free(var.varname);
1516 			if (targetVarsEnabled)
1517 				return true;
1518 		}
1519 
1520 		/*
1521 		 * The targets take real sources, so we must beware of archive
1522 		 * specifications (i.e. things with left parentheses in them)
1523 		 * and handle them accordingly.
1524 		 */
1525 		for (; *end != '\0' && !ch_isspace(*end); end++) {
1526 			if (*end == '(' && end > start && end[-1] != '$') {
1527 				/*
1528 				 * Only stop for a left parenthesis if it
1529 				 * isn't at the start of a word (that'll be
1530 				 * for variable changes later) and isn't
1531 				 * preceded by a dollar sign (a dynamic
1532 				 * source).
1533 				 */
1534 				break;
1535 			}
1536 		}
1537 
1538 		if (*end == '(') {
1539 			GNodeList sources = LST_INIT;
1540 			if (!Arch_ParseArchive(&start, &sources,
1541 			    SCOPE_CMDLINE)) {
1542 				Parse_Error(PARSE_FATAL,
1543 				    "Error in source archive spec \"%s\"",
1544 				    start);
1545 				return false;
1546 			}
1547 
1548 			while (!Lst_IsEmpty(&sources)) {
1549 				GNode *gn = Lst_Dequeue(&sources);
1550 				ApplyDependencySource(targetAttr, gn->name,
1551 				    special);
1552 			}
1553 			Lst_Done(&sources);
1554 			end = start;
1555 		} else {
1556 			if (*end != '\0') {
1557 				*end = '\0';
1558 				end++;
1559 			}
1560 
1561 			ApplyDependencySource(targetAttr, start, special);
1562 		}
1563 		pp_skip_whitespace(&end);
1564 		start = end;
1565 	}
1566 	return true;
1567 }
1568 
1569 /*
1570  * From a dependency line like 'targets: sources', parse the sources.
1571  *
1572  * See the tests depsrc-*.mk.
1573  */
1574 static void
1575 ParseDependencySources(char *p, GNodeType targetAttr,
1576 		       ParseSpecial special, SearchPathList **inout_paths)
1577 {
1578 	if (*p == '\0') {
1579 		HandleDependencySourcesEmpty(special, *inout_paths);
1580 	} else if (special == SP_MFLAGS) {
1581 		Main_ParseArgLine(p);
1582 		return;
1583 	} else if (special == SP_SHELL) {
1584 		if (!Job_ParseShell(p)) {
1585 			Parse_Error(PARSE_FATAL,
1586 			    "improper shell specification");
1587 			return;
1588 		}
1589 		return;
1590 	} else if (special == SP_NOTPARALLEL || special == SP_SINGLESHELL ||
1591 		   special == SP_DELETE_ON_ERROR) {
1592 		return;
1593 	}
1594 
1595 	switch (special) {
1596 	case SP_INCLUDES:
1597 	case SP_LIBS:
1598 	case SP_NOREADONLY:
1599 	case SP_NULL:
1600 	case SP_OBJDIR:
1601 	case SP_PATH:
1602 	case SP_READONLY:
1603 	case SP_SUFFIXES:
1604 	case SP_SYSPATH:
1605 		ParseDependencySourcesSpecial(p, special, *inout_paths);
1606 		if (*inout_paths != NULL) {
1607 			Lst_Free(*inout_paths);
1608 			*inout_paths = NULL;
1609 		}
1610 		if (special == SP_PATH)
1611 			Dir_SetPATH();
1612 		if (special == SP_SYSPATH)
1613 			Dir_SetSYSPATH();
1614 		break;
1615 	default:
1616 		assert(*inout_paths == NULL);
1617 		if (!ParseDependencySourcesMundane(p, special, targetAttr))
1618 			return;
1619 		break;
1620 	}
1621 
1622 	MaybeUpdateMainTarget();
1623 }
1624 
1625 /*
1626  * Parse a dependency line consisting of targets, followed by a dependency
1627  * operator, optionally followed by sources.
1628  *
1629  * The nodes of the sources are linked as children to the nodes of the
1630  * targets. Nodes are created as necessary.
1631  *
1632  * The operator is applied to each node in the global 'targets' list,
1633  * which is where the nodes found for the targets are kept.
1634  *
1635  * The sources are parsed in much the same way as the targets, except
1636  * that they are expanded using the wildcarding scheme of the C-Shell,
1637  * and a target is created for each expanded word. Each of the resulting
1638  * nodes is then linked to each of the targets as one of its children.
1639  *
1640  * Certain targets and sources such as .PHONY or .PRECIOUS are handled
1641  * specially, see ParseSpecial.
1642  *
1643  * Transformation rules such as '.c.o' are also handled here, see
1644  * Suff_AddTransform.
1645  *
1646  * Upon return, the value of the line is unspecified.
1647  */
1648 static void
1649 ParseDependency(char *line, const char *unexpanded_line)
1650 {
1651 	char *p;
1652 	SearchPathList *paths;	/* search paths to alter when parsing a list
1653 				 * of .PATH targets */
1654 	GNodeType targetAttr;	/* from special sources */
1655 	ParseSpecial special;	/* in special targets, the children are
1656 				 * linked as children of the parent but not
1657 				 * vice versa */
1658 	GNodeType op;
1659 
1660 	DEBUG1(PARSE, "ParseDependency(%s)\n", line);
1661 	p = line;
1662 	paths = NULL;
1663 	targetAttr = OP_NONE;
1664 	special = SP_NOT;
1665 
1666 	if (!ParseDependencyTargets(&p, line, &special, &targetAttr, &paths,
1667 	    unexpanded_line))
1668 		goto out;
1669 
1670 	if (!Lst_IsEmpty(targets))
1671 		CheckSpecialMundaneMixture(special);
1672 
1673 	op = ParseDependencyOp(&p);
1674 	if (op == OP_NONE) {
1675 		InvalidLineType(line, unexpanded_line);
1676 		goto out;
1677 	}
1678 	ApplyDependencyOperator(op);
1679 
1680 	pp_skip_whitespace(&p);
1681 
1682 	ParseDependencySources(p, targetAttr, special, &paths);
1683 
1684 out:
1685 	if (paths != NULL)
1686 		Lst_Free(paths);
1687 }
1688 
1689 /*
1690  * Determine the assignment operator and adjust the end of the variable
1691  * name accordingly.
1692  */
1693 static VarAssign
1694 AdjustVarassignOp(const char *name, const char *nameEnd, const char *op,
1695 		  const char *value)
1696 {
1697 	VarAssignOp type;
1698 	VarAssign va;
1699 
1700 	if (op > name && op[-1] == '+') {
1701 		op--;
1702 		type = VAR_APPEND;
1703 
1704 	} else if (op > name && op[-1] == '?') {
1705 		op--;
1706 		type = VAR_DEFAULT;
1707 
1708 	} else if (op > name && op[-1] == ':') {
1709 		op--;
1710 		type = VAR_SUBST;
1711 
1712 	} else if (op > name && op[-1] == '!') {
1713 		op--;
1714 		type = VAR_SHELL;
1715 
1716 	} else {
1717 		type = VAR_NORMAL;
1718 #ifdef SUNSHCMD
1719 		while (op > name && ch_isspace(op[-1]))
1720 			op--;
1721 
1722 		if (op - name >= 3 && memcmp(op - 3, ":sh", 3) == 0) {
1723 			op -= 3;
1724 			type = VAR_SHELL;
1725 		}
1726 #endif
1727 	}
1728 
1729 	va.varname = bmake_strsedup(name, nameEnd < op ? nameEnd : op);
1730 	va.op = type;
1731 	va.value = value;
1732 	return va;
1733 }
1734 
1735 /*
1736  * Parse a variable assignment, consisting of a single-word variable name,
1737  * optional whitespace, an assignment operator, optional whitespace and the
1738  * variable value.
1739  *
1740  * Note: There is a lexical ambiguity with assignment modifier characters
1741  * in variable names. This routine interprets the character before the =
1742  * as a modifier. Therefore, an assignment like
1743  *	C++=/usr/bin/CC
1744  * is interpreted as "C+ +=" instead of "C++ =".
1745  *
1746  * Used for both lines in a file and command line arguments.
1747  */
1748 static bool
1749 Parse_IsVar(const char *p, VarAssign *out_var)
1750 {
1751 	const char *nameStart, *nameEnd, *firstSpace, *eq;
1752 	int level = 0;
1753 
1754 	cpp_skip_hspace(&p);	/* Skip to variable name */
1755 
1756 	/*
1757 	 * During parsing, the '+' of the operator '+=' is initially parsed
1758 	 * as part of the variable name.  It is later corrected, as is the
1759 	 * ':sh' modifier. Of these two (nameEnd and eq), the earlier one
1760 	 * determines the actual end of the variable name.
1761 	 */
1762 
1763 	nameStart = p;
1764 	firstSpace = NULL;
1765 
1766 	/* Scan for one of the assignment operators outside an expression. */
1767 	while (*p != '\0') {
1768 		char ch = *p++;
1769 		if (ch == '(' || ch == '{') {
1770 			level++;
1771 			continue;
1772 		}
1773 		if (ch == ')' || ch == '}') {
1774 			level--;
1775 			continue;
1776 		}
1777 
1778 		if (level != 0)
1779 			continue;
1780 
1781 		if ((ch == ' ' || ch == '\t') && firstSpace == NULL)
1782 			firstSpace = p - 1;
1783 		while (ch == ' ' || ch == '\t')
1784 			ch = *p++;
1785 
1786 		if (ch == '\0')
1787 			return false;
1788 #ifdef SUNSHCMD
1789 		if (ch == ':' && p[0] == 's' && p[1] == 'h') {
1790 			p += 2;
1791 			continue;
1792 		}
1793 #endif
1794 		if (ch == '=')
1795 			eq = p - 1;
1796 		else if (*p == '=' &&
1797 		    (ch == '+' || ch == ':' || ch == '?' || ch == '!'))
1798 			eq = p;
1799 		else if (firstSpace != NULL)
1800 			return false;
1801 		else
1802 			continue;
1803 
1804 		nameEnd = firstSpace != NULL ? firstSpace : eq;
1805 		p = eq + 1;
1806 		cpp_skip_whitespace(&p);
1807 		*out_var = AdjustVarassignOp(nameStart, nameEnd, eq, p);
1808 		return true;
1809 	}
1810 
1811 	return false;
1812 }
1813 
1814 /*
1815  * Check for syntax errors such as unclosed expressions or unknown modifiers.
1816  */
1817 static void
1818 VarCheckSyntax(VarAssignOp op, const char *uvalue, GNode *scope)
1819 {
1820 	if (opts.strict) {
1821 		if (op != VAR_SUBST && strchr(uvalue, '$') != NULL) {
1822 			char *parsedValue = Var_Subst(uvalue,
1823 			    scope, VARE_PARSE_ONLY);
1824 			/* TODO: handle errors */
1825 			free(parsedValue);
1826 		}
1827 	}
1828 }
1829 
1830 /* Perform a variable assignment that uses the operator ':='. */
1831 static void
1832 VarAssign_EvalSubst(GNode *scope, const char *name, const char *uvalue,
1833 		    FStr *out_avalue)
1834 {
1835 	char *evalue;
1836 
1837 	/*
1838 	 * Make sure that we set the variable the first time to nothing
1839 	 * so that it gets substituted.
1840 	 *
1841 	 * TODO: Add a test that demonstrates why this code is needed,
1842 	 *  apart from making the debug log longer.
1843 	 *
1844 	 * XXX: The variable name is expanded up to 3 times.
1845 	 */
1846 	if (!Var_ExistsExpand(scope, name))
1847 		Var_SetExpand(scope, name, "");
1848 
1849 	evalue = Var_Subst(uvalue, scope, VARE_KEEP_DOLLAR_UNDEF);
1850 	/* TODO: handle errors */
1851 
1852 	Var_SetExpand(scope, name, evalue);
1853 
1854 	*out_avalue = FStr_InitOwn(evalue);
1855 }
1856 
1857 /* Perform a variable assignment that uses the operator '!='. */
1858 static void
1859 VarAssign_EvalShell(const char *name, const char *uvalue, GNode *scope,
1860 		    FStr *out_avalue)
1861 {
1862 	FStr cmd;
1863 	char *output, *error;
1864 
1865 	cmd = FStr_InitRefer(uvalue);
1866 	Var_Expand(&cmd, SCOPE_CMDLINE, VARE_UNDEFERR);
1867 
1868 	output = Cmd_Exec(cmd.str, &error);
1869 	Var_SetExpand(scope, name, output);
1870 	*out_avalue = FStr_InitOwn(output);
1871 	if (error != NULL) {
1872 		Parse_Error(PARSE_WARNING, "%s", error);
1873 		free(error);
1874 	}
1875 
1876 	FStr_Done(&cmd);
1877 }
1878 
1879 /*
1880  * Perform a variable assignment.
1881  *
1882  * The actual value of the variable is returned in *out_true_avalue.
1883  * Especially for VAR_SUBST and VAR_SHELL this can differ from the literal
1884  * value.
1885  *
1886  * Return whether the assignment was actually performed, which is usually
1887  * the case.  It is only skipped if the operator is '?=' and the variable
1888  * already exists.
1889  */
1890 static bool
1891 VarAssign_Eval(const char *name, VarAssignOp op, const char *uvalue,
1892 	       GNode *scope, FStr *out_true_avalue)
1893 {
1894 	FStr avalue = FStr_InitRefer(uvalue);
1895 
1896 	if (op == VAR_APPEND)
1897 		Var_AppendExpand(scope, name, uvalue);
1898 	else if (op == VAR_SUBST)
1899 		VarAssign_EvalSubst(scope, name, uvalue, &avalue);
1900 	else if (op == VAR_SHELL)
1901 		VarAssign_EvalShell(name, uvalue, scope, &avalue);
1902 	else {
1903 		/* XXX: The variable name is expanded up to 2 times. */
1904 		if (op == VAR_DEFAULT && Var_ExistsExpand(scope, name))
1905 			return false;
1906 
1907 		/* Normal assignment -- just do it. */
1908 		Var_SetExpand(scope, name, uvalue);
1909 	}
1910 
1911 	*out_true_avalue = avalue;
1912 	return true;
1913 }
1914 
1915 static void
1916 VarAssignSpecial(const char *name, const char *avalue)
1917 {
1918 	if (strcmp(name, ".MAKEOVERRIDES") == 0)
1919 		Main_ExportMAKEFLAGS(false);	/* re-export MAKEFLAGS */
1920 	else if (strcmp(name, ".CURDIR") == 0) {
1921 		/*
1922 		 * Someone is being (too?) clever...
1923 		 * Let's pretend they know what they are doing and
1924 		 * re-initialize the 'cur' CachedDir.
1925 		 */
1926 		Dir_InitCur(avalue);
1927 		Dir_SetPATH();
1928 	} else if (strcmp(name, ".MAKE.JOB.PREFIX") == 0)
1929 		Job_SetPrefix();
1930 	else if (strcmp(name, ".MAKE.EXPORTED") == 0)
1931 		Var_ExportVars(avalue);
1932 }
1933 
1934 /* Perform the variable assignment in the given scope. */
1935 static void
1936 Parse_Var(VarAssign *var, GNode *scope)
1937 {
1938 	FStr avalue;		/* actual value (maybe expanded) */
1939 
1940 	VarCheckSyntax(var->op, var->value, scope);
1941 	if (VarAssign_Eval(var->varname, var->op, var->value, scope, &avalue)) {
1942 		VarAssignSpecial(var->varname, avalue.str);
1943 		FStr_Done(&avalue);
1944 	}
1945 }
1946 
1947 
1948 /*
1949  * See if the command possibly calls a sub-make by using the
1950  * expressions ${.MAKE}, ${MAKE} or the plain word "make".
1951  */
1952 static bool
1953 MaybeSubMake(const char *cmd)
1954 {
1955 	const char *start;
1956 
1957 	for (start = cmd; *start != '\0'; start++) {
1958 		const char *p = start;
1959 		char endc;
1960 
1961 		/* XXX: What if progname != "make"? */
1962 		if (strncmp(p, "make", 4) == 0)
1963 			if (start == cmd || !ch_isalnum(p[-1]))
1964 				if (!ch_isalnum(p[4]))
1965 					return true;
1966 
1967 		if (*p != '$')
1968 			continue;
1969 		p++;
1970 
1971 		if (*p == '{')
1972 			endc = '}';
1973 		else if (*p == '(')
1974 			endc = ')';
1975 		else
1976 			continue;
1977 		p++;
1978 
1979 		if (*p == '.')	/* Accept either ${.MAKE} or ${MAKE}. */
1980 			p++;
1981 
1982 		if (strncmp(p, "MAKE", 4) == 0 && p[4] == endc)
1983 			return true;
1984 	}
1985 	return false;
1986 }
1987 
1988 /* Append the command to the target node. */
1989 static void
1990 GNode_AddCommand(GNode *gn, char *cmd)
1991 {
1992 	if ((gn->type & OP_DOUBLEDEP) && gn->cohorts.last != NULL)
1993 		gn = gn->cohorts.last->datum;
1994 
1995 	/* if target already supplied, ignore commands */
1996 	if (!(gn->type & OP_HAS_COMMANDS)) {
1997 		Lst_Append(&gn->commands, cmd);
1998 		if (MaybeSubMake(cmd))
1999 			gn->type |= OP_SUBMAKE;
2000 		RememberLocation(gn);
2001 	} else {
2002 		Parse_Error(PARSE_WARNING,
2003 		    "duplicate script for target \"%s\" ignored",
2004 		    gn->name);
2005 		ParseErrorInternal(gn, PARSE_WARNING,
2006 		    "using previous script for \"%s\" defined here",
2007 		    gn->name);
2008 	}
2009 }
2010 
2011 /*
2012  * Parse a directive like '.include' or '.-include'.
2013  *
2014  * .include "user-makefile.mk"
2015  * .include <system-makefile.mk>
2016  */
2017 static void
2018 ParseInclude(char *directive)
2019 {
2020 	char endc;		/* '>' or '"' */
2021 	char *p;
2022 	bool silent = directive[0] != 'i';
2023 	FStr file;
2024 
2025 	p = directive + (silent ? 8 : 7);
2026 	pp_skip_hspace(&p);
2027 
2028 	if (*p != '"' && *p != '<') {
2029 		Parse_Error(PARSE_FATAL,
2030 		    ".include filename must be delimited by '\"' or '<'");
2031 		return;
2032 	}
2033 
2034 	endc = *p++ == '<' ? '>' : '"';
2035 	file = FStr_InitRefer(p);
2036 
2037 	while (*p != '\0' && *p != endc)
2038 		p++;
2039 
2040 	if (*p != endc) {
2041 		Parse_Error(PARSE_FATAL,
2042 		    "Unclosed .include filename. '%c' expected", endc);
2043 		return;
2044 	}
2045 
2046 	*p = '\0';
2047 
2048 	Var_Expand(&file, SCOPE_CMDLINE, VARE_WANTRES);
2049 	IncludeFile(file.str, endc == '>', directive[0] == 'd', silent);
2050 	FStr_Done(&file);
2051 }
2052 
2053 /*
2054  * Split filename into dirname + basename, then assign these to the
2055  * given variables.
2056  */
2057 static void
2058 SetFilenameVars(const char *filename, const char *dirvar, const char *filevar)
2059 {
2060 	const char *slash, *basename;
2061 	FStr dirname;
2062 
2063 	slash = strrchr(filename, '/');
2064 	if (slash == NULL) {
2065 		dirname = FStr_InitRefer(curdir);
2066 		basename = filename;
2067 	} else {
2068 		dirname = FStr_InitOwn(bmake_strsedup(filename, slash));
2069 		basename = slash + 1;
2070 	}
2071 
2072 	Global_Set(dirvar, dirname.str);
2073 	Global_Set(filevar, basename);
2074 
2075 	DEBUG4(PARSE, "SetFilenameVars: ${%s} = `%s' ${%s} = `%s'\n",
2076 	    dirvar, dirname.str, filevar, basename);
2077 	FStr_Done(&dirname);
2078 }
2079 
2080 /*
2081  * Return the immediately including file.
2082  *
2083  * This is made complicated since the .for loop is implemented as a special
2084  * kind of .include; see For_Run.
2085  */
2086 static const char *
2087 GetActuallyIncludingFile(void)
2088 {
2089 	size_t i;
2090 	const IncludedFile *incs = GetInclude(0);
2091 
2092 	for (i = includes.len; i >= 2; i--)
2093 		if (incs[i - 1].forLoop == NULL)
2094 			return incs[i - 2].name.str;
2095 	return NULL;
2096 }
2097 
2098 /* Set .PARSEDIR, .PARSEFILE, .INCLUDEDFROMDIR and .INCLUDEDFROMFILE. */
2099 static void
2100 SetParseFile(const char *filename)
2101 {
2102 	const char *including;
2103 
2104 	SetFilenameVars(filename, ".PARSEDIR", ".PARSEFILE");
2105 
2106 	including = GetActuallyIncludingFile();
2107 	if (including != NULL) {
2108 		SetFilenameVars(including,
2109 		    ".INCLUDEDFROMDIR", ".INCLUDEDFROMFILE");
2110 	} else {
2111 		Global_Delete(".INCLUDEDFROMDIR");
2112 		Global_Delete(".INCLUDEDFROMFILE");
2113 	}
2114 }
2115 
2116 static bool
2117 StrContainsWord(const char *str, const char *word)
2118 {
2119 	size_t strLen = strlen(str);
2120 	size_t wordLen = strlen(word);
2121 	const char *p;
2122 
2123 	if (strLen < wordLen)
2124 		return false;
2125 
2126 	for (p = str; p != NULL; p = strchr(p, ' ')) {
2127 		if (*p == ' ')
2128 			p++;
2129 		if (p > str + strLen - wordLen)
2130 			return false;
2131 
2132 		if (memcmp(p, word, wordLen) == 0 &&
2133 		    (p[wordLen] == '\0' || p[wordLen] == ' '))
2134 			return true;
2135 	}
2136 	return false;
2137 }
2138 
2139 /*
2140  * XXX: Searching through a set of words with this linear search is
2141  * inefficient for variables that contain thousands of words.
2142  *
2143  * XXX: The paths in this list don't seem to be normalized in any way.
2144  */
2145 static bool
2146 VarContainsWord(const char *varname, const char *word)
2147 {
2148 	FStr val = Var_Value(SCOPE_GLOBAL, varname);
2149 	bool found = val.str != NULL && StrContainsWord(val.str, word);
2150 	FStr_Done(&val);
2151 	return found;
2152 }
2153 
2154 /*
2155  * Track the makefiles we read - so makefiles can set dependencies on them.
2156  * Avoid adding anything more than once.
2157  *
2158  * Time complexity: O(n) per call, in total O(n^2), where n is the number
2159  * of makefiles that have been loaded.
2160  */
2161 static void
2162 TrackInput(const char *name)
2163 {
2164 	if (!VarContainsWord(".MAKE.MAKEFILES", name))
2165 		Global_Append(".MAKE.MAKEFILES", name);
2166 }
2167 
2168 
2169 /* Parse from the given buffer, later return to the current file. */
2170 void
2171 Parse_PushInput(const char *name, unsigned lineno, unsigned readLines,
2172 		Buffer buf, struct ForLoop *forLoop)
2173 {
2174 	IncludedFile *curFile;
2175 
2176 	if (forLoop != NULL)
2177 		name = CurFile()->name.str;
2178 	else
2179 		TrackInput(name);
2180 
2181 	DEBUG3(PARSE, "Parse_PushInput: %s %s, line %u\n",
2182 	    forLoop != NULL ? ".for loop in": "file", name, lineno);
2183 
2184 	curFile = Vector_Push(&includes);
2185 	curFile->name = FStr_InitOwn(bmake_strdup(name));
2186 	curFile->lineno = lineno;
2187 	curFile->readLines = readLines;
2188 	curFile->forHeadLineno = lineno;
2189 	curFile->forBodyReadLines = readLines;
2190 	curFile->buf = buf;
2191 	curFile->depending = doing_depend;	/* restore this on EOF */
2192 	curFile->guardState = forLoop == NULL ? GS_START : GS_NO;
2193 	curFile->guard = NULL;
2194 	curFile->forLoop = forLoop;
2195 
2196 	if (forLoop != NULL && !For_NextIteration(forLoop, &curFile->buf))
2197 		abort();	/* see For_Run */
2198 
2199 	curFile->buf_ptr = curFile->buf.data;
2200 	curFile->buf_end = curFile->buf.data + curFile->buf.len;
2201 	curFile->condMinDepth = cond_depth;
2202 	SetParseFile(name);
2203 }
2204 
2205 /* Check if the directive is an include directive. */
2206 static bool
2207 IsInclude(const char *dir, bool sysv)
2208 {
2209 	if (dir[0] == 's' || dir[0] == '-' || (dir[0] == 'd' && !sysv))
2210 		dir++;
2211 
2212 	if (strncmp(dir, "include", 7) != 0)
2213 		return false;
2214 
2215 	/* Space is not mandatory for BSD .include */
2216 	return !sysv || ch_isspace(dir[7]);
2217 }
2218 
2219 
2220 #ifdef SYSVINCLUDE
2221 /* Check if the line is a SYSV include directive. */
2222 static bool
2223 IsSysVInclude(const char *line)
2224 {
2225 	const char *p;
2226 
2227 	if (!IsInclude(line, true))
2228 		return false;
2229 
2230 	/* Avoid interpreting a dependency line as an include */
2231 	for (p = line; (p = strchr(p, ':')) != NULL;) {
2232 
2233 		/* end of line -> it's a dependency */
2234 		if (*++p == '\0')
2235 			return false;
2236 
2237 		/* '::' operator or ': ' -> it's a dependency */
2238 		if (*p == ':' || ch_isspace(*p))
2239 			return false;
2240 	}
2241 	return true;
2242 }
2243 
2244 /* Push to another file.  The line points to the word "include". */
2245 static void
2246 ParseTraditionalInclude(char *line)
2247 {
2248 	char *p;		/* current position in file spec */
2249 	bool done = false;
2250 	bool silent = line[0] != 'i';
2251 	char *file = line + (silent ? 8 : 7);
2252 	char *all_files;
2253 
2254 	DEBUG1(PARSE, "ParseTraditionalInclude: %s\n", file);
2255 
2256 	pp_skip_whitespace(&file);
2257 
2258 	all_files = Var_Subst(file, SCOPE_CMDLINE, VARE_WANTRES);
2259 	/* TODO: handle errors */
2260 
2261 	for (file = all_files; !done; file = p + 1) {
2262 		/* Skip to end of line or next whitespace */
2263 		for (p = file; *p != '\0' && !ch_isspace(*p); p++)
2264 			continue;
2265 
2266 		if (*p != '\0')
2267 			*p = '\0';
2268 		else
2269 			done = true;
2270 
2271 		IncludeFile(file, false, false, silent);
2272 	}
2273 
2274 	free(all_files);
2275 }
2276 #endif
2277 
2278 #ifdef GMAKEEXPORT
2279 /* Parse "export <variable>=<value>", and actually export it. */
2280 static void
2281 ParseGmakeExport(char *line)
2282 {
2283 	char *variable = line + 6;
2284 	char *value;
2285 
2286 	DEBUG1(PARSE, "ParseGmakeExport: %s\n", variable);
2287 
2288 	pp_skip_whitespace(&variable);
2289 
2290 	for (value = variable; *value != '\0' && *value != '='; value++)
2291 		continue;
2292 
2293 	if (*value != '=') {
2294 		Parse_Error(PARSE_FATAL,
2295 		    "Variable/Value missing from \"export\"");
2296 		return;
2297 	}
2298 	*value++ = '\0';	/* terminate variable */
2299 
2300 	/*
2301 	 * Expand the value before putting it in the environment.
2302 	 */
2303 	value = Var_Subst(value, SCOPE_CMDLINE, VARE_WANTRES);
2304 	/* TODO: handle errors */
2305 
2306 	setenv(variable, value, 1);
2307 	free(value);
2308 }
2309 #endif
2310 
2311 /*
2312  * When the end of the current file or .for loop is reached, continue reading
2313  * the previous file at the previous location.
2314  *
2315  * Results:
2316  *	true to continue parsing, i.e. it had only reached the end of an
2317  *	included file, false if the main file has been parsed completely.
2318  */
2319 static bool
2320 ParseEOF(void)
2321 {
2322 	IncludedFile *curFile = CurFile();
2323 
2324 	doing_depend = curFile->depending;
2325 	if (curFile->forLoop != NULL &&
2326 	    For_NextIteration(curFile->forLoop, &curFile->buf)) {
2327 		curFile->buf_ptr = curFile->buf.data;
2328 		curFile->buf_end = curFile->buf.data + curFile->buf.len;
2329 		curFile->readLines = curFile->forBodyReadLines;
2330 		return true;
2331 	}
2332 
2333 	Cond_EndFile();
2334 
2335 	if (curFile->guardState == GS_DONE)
2336 		HashTable_Set(&guards, curFile->name.str, curFile->guard);
2337 	else if (curFile->guard != NULL) {
2338 		free(curFile->guard->name);
2339 		free(curFile->guard);
2340 	}
2341 
2342 	FStr_Done(&curFile->name);
2343 	Buf_Done(&curFile->buf);
2344 	if (curFile->forLoop != NULL)
2345 		ForLoop_Free(curFile->forLoop);
2346 	Vector_Pop(&includes);
2347 
2348 	if (includes.len == 0) {
2349 		/* We've run out of input */
2350 		Global_Delete(".PARSEDIR");
2351 		Global_Delete(".PARSEFILE");
2352 		Global_Delete(".INCLUDEDFROMDIR");
2353 		Global_Delete(".INCLUDEDFROMFILE");
2354 		return false;
2355 	}
2356 
2357 	curFile = CurFile();
2358 	DEBUG2(PARSE, "ParseEOF: returning to file %s, line %u\n",
2359 	    curFile->name.str, curFile->readLines + 1);
2360 
2361 	SetParseFile(curFile->name.str);
2362 	return true;
2363 }
2364 
2365 typedef enum ParseRawLineResult {
2366 	PRLR_LINE,
2367 	PRLR_EOF,
2368 	PRLR_ERROR
2369 } ParseRawLineResult;
2370 
2371 /*
2372  * Parse until the end of a line, taking into account lines that end with
2373  * backslash-newline.  The resulting line goes from out_line to out_line_end;
2374  * the line is not null-terminated.
2375  */
2376 static ParseRawLineResult
2377 ParseRawLine(IncludedFile *curFile, char **out_line, char **out_line_end,
2378 	     char **out_firstBackslash, char **out_commentLineEnd)
2379 {
2380 	char *line = curFile->buf_ptr;
2381 	char *buf_end = curFile->buf_end;
2382 	char *p = line;
2383 	char *line_end = line;
2384 	char *firstBackslash = NULL;
2385 	char *commentLineEnd = NULL;
2386 	ParseRawLineResult res = PRLR_LINE;
2387 
2388 	curFile->readLines++;
2389 
2390 	for (;;) {
2391 		char ch;
2392 
2393 		if (p == buf_end) {
2394 			res = PRLR_EOF;
2395 			break;
2396 		}
2397 
2398 		ch = *p;
2399 		if (ch == '\0' || (ch == '\\' && p[1] == '\0')) {
2400 			Parse_Error(PARSE_FATAL, "Zero byte read from file");
2401 			return PRLR_ERROR;
2402 		}
2403 
2404 		/* Treat next character after '\' as literal. */
2405 		if (ch == '\\') {
2406 			if (firstBackslash == NULL)
2407 				firstBackslash = p;
2408 			if (p[1] == '\n') {
2409 				curFile->readLines++;
2410 				if (p + 2 == buf_end) {
2411 					line_end = p;
2412 					*line_end = '\n';
2413 					p += 2;
2414 					continue;
2415 				}
2416 			}
2417 			p += 2;
2418 			line_end = p;
2419 			assert(p <= buf_end);
2420 			continue;
2421 		}
2422 
2423 		/*
2424 		 * Remember the first '#' for comment stripping, unless
2425 		 * the previous char was '[', as in the modifier ':[#]'.
2426 		 */
2427 		if (ch == '#' && commentLineEnd == NULL &&
2428 		    !(p > line && p[-1] == '['))
2429 			commentLineEnd = line_end;
2430 
2431 		p++;
2432 		if (ch == '\n')
2433 			break;
2434 
2435 		/* We are not interested in trailing whitespace. */
2436 		if (!ch_isspace(ch))
2437 			line_end = p;
2438 	}
2439 
2440 	curFile->buf_ptr = p;
2441 	*out_line = line;
2442 	*out_line_end = line_end;
2443 	*out_firstBackslash = firstBackslash;
2444 	*out_commentLineEnd = commentLineEnd;
2445 	return res;
2446 }
2447 
2448 /*
2449  * Beginning at start, unescape '\#' to '#' and replace backslash-newline
2450  * with a single space.
2451  */
2452 static void
2453 UnescapeBackslash(char *line, char *start)
2454 {
2455 	const char *src = start;
2456 	char *dst = start;
2457 	char *spaceStart = line;
2458 
2459 	for (;;) {
2460 		char ch = *src++;
2461 		if (ch != '\\') {
2462 			if (ch == '\0')
2463 				break;
2464 			*dst++ = ch;
2465 			continue;
2466 		}
2467 
2468 		ch = *src++;
2469 		if (ch == '\0') {
2470 			/* Delete '\\' at the end of the buffer. */
2471 			dst--;
2472 			break;
2473 		}
2474 
2475 		/* Delete '\\' from before '#' on non-command lines. */
2476 		if (ch == '#' && line[0] != '\t')
2477 			*dst++ = ch;
2478 		else if (ch == '\n') {
2479 			cpp_skip_hspace(&src);
2480 			*dst++ = ' ';
2481 		} else {
2482 			/* Leave '\\' in the buffer for later. */
2483 			*dst++ = '\\';
2484 			*dst++ = ch;
2485 			/* Keep an escaped ' ' at the line end. */
2486 			spaceStart = dst;
2487 		}
2488 	}
2489 
2490 	/* Delete any trailing spaces - eg from empty continuations */
2491 	while (dst > spaceStart && ch_isspace(dst[-1]))
2492 		dst--;
2493 	*dst = '\0';
2494 }
2495 
2496 typedef enum LineKind {
2497 	/*
2498 	 * Return the next line that is neither empty nor a comment.
2499 	 * Backslash line continuations are folded into a single space.
2500 	 * A trailing comment, if any, is discarded.
2501 	 */
2502 	LK_NONEMPTY,
2503 
2504 	/*
2505 	 * Return the next line, even if it is empty or a comment.
2506 	 * Preserve backslash-newline to keep the line numbers correct.
2507 	 *
2508 	 * Used in .for loops to collect the body of the loop while waiting
2509 	 * for the corresponding .endfor.
2510 	 */
2511 	LK_FOR_BODY,
2512 
2513 	/*
2514 	 * Return the next line that starts with a dot.
2515 	 * Backslash line continuations are folded into a single space.
2516 	 * A trailing comment, if any, is discarded.
2517 	 *
2518 	 * Used in .if directives to skip over irrelevant branches while
2519 	 * waiting for the corresponding .endif.
2520 	 */
2521 	LK_DOT
2522 } LineKind;
2523 
2524 /*
2525  * Return the next "interesting" logical line from the current file.  The
2526  * returned string will be freed at the end of including the file.
2527  */
2528 static char *
2529 ReadLowLevelLine(LineKind kind)
2530 {
2531 	IncludedFile *curFile = CurFile();
2532 	ParseRawLineResult res;
2533 	char *line;
2534 	char *line_end;
2535 	char *firstBackslash;
2536 	char *commentLineEnd;
2537 
2538 	for (;;) {
2539 		curFile->lineno = curFile->readLines + 1;
2540 		res = ParseRawLine(curFile,
2541 		    &line, &line_end, &firstBackslash, &commentLineEnd);
2542 		if (res == PRLR_ERROR)
2543 			return NULL;
2544 
2545 		if (line == line_end || line == commentLineEnd) {
2546 			if (res == PRLR_EOF)
2547 				return NULL;
2548 			if (kind != LK_FOR_BODY)
2549 				continue;
2550 		}
2551 
2552 		/* We now have a line of data */
2553 		assert(ch_isspace(*line_end));
2554 		*line_end = '\0';
2555 
2556 		if (kind == LK_FOR_BODY)
2557 			return line;	/* Don't join the physical lines. */
2558 
2559 		if (kind == LK_DOT && line[0] != '.')
2560 			continue;
2561 		break;
2562 	}
2563 
2564 	if (commentLineEnd != NULL && line[0] != '\t')
2565 		*commentLineEnd = '\0';
2566 	if (firstBackslash != NULL)
2567 		UnescapeBackslash(line, firstBackslash);
2568 	return line;
2569 }
2570 
2571 static bool
2572 SkipIrrelevantBranches(void)
2573 {
2574 	const char *line;
2575 
2576 	while ((line = ReadLowLevelLine(LK_DOT)) != NULL)
2577 		if (Cond_EvalLine(line) == CR_TRUE)
2578 			return true;
2579 	return false;
2580 }
2581 
2582 static bool
2583 ParseForLoop(const char *line)
2584 {
2585 	int rval;
2586 	unsigned forHeadLineno;
2587 	unsigned bodyReadLines;
2588 	int forLevel;
2589 
2590 	rval = For_Eval(line);
2591 	if (rval == 0)
2592 		return false;	/* Not a .for line */
2593 	if (rval < 0)
2594 		return true;	/* Syntax error - error printed, ignore line */
2595 
2596 	forHeadLineno = CurFile()->lineno;
2597 	bodyReadLines = CurFile()->readLines;
2598 
2599 	/* Accumulate the loop body until the matching '.endfor'. */
2600 	forLevel = 1;
2601 	do {
2602 		line = ReadLowLevelLine(LK_FOR_BODY);
2603 		if (line == NULL) {
2604 			Parse_Error(PARSE_FATAL,
2605 			    "Unexpected end of file in .for loop");
2606 			break;
2607 		}
2608 	} while (For_Accum(line, &forLevel));
2609 
2610 	For_Run(forHeadLineno, bodyReadLines);
2611 	return true;
2612 }
2613 
2614 /*
2615  * Read an entire line from the input file.
2616  *
2617  * Empty lines, .if and .for are handled by this function, while variable
2618  * assignments, other directives, dependency lines and shell commands are
2619  * handled by the caller.
2620  *
2621  * Return a line without trailing whitespace, or NULL for EOF.  The returned
2622  * string will be freed at the end of including the file.
2623  */
2624 static char *
2625 ReadHighLevelLine(void)
2626 {
2627 	char *line;
2628 	CondResult condResult;
2629 
2630 	for (;;) {
2631 		IncludedFile *curFile = CurFile();
2632 		line = ReadLowLevelLine(LK_NONEMPTY);
2633 		if (posix_state == PS_MAYBE_NEXT_LINE)
2634 			posix_state = PS_NOW_OR_NEVER;
2635 		else
2636 			posix_state = PS_TOO_LATE;
2637 		if (line == NULL)
2638 			return NULL;
2639 
2640 		if (curFile->guardState != GS_NO
2641 		    && ((curFile->guardState == GS_START && line[0] != '.')
2642 			|| curFile->guardState == GS_DONE))
2643 			curFile->guardState = GS_NO;
2644 		if (line[0] != '.')
2645 			return line;
2646 
2647 		condResult = Cond_EvalLine(line);
2648 		if (curFile->guardState == GS_START) {
2649 			Guard *guard;
2650 			if (condResult != CR_ERROR
2651 			    && (guard = Cond_ExtractGuard(line)) != NULL) {
2652 				curFile->guardState = GS_COND;
2653 				curFile->guard = guard;
2654 			} else
2655 				curFile->guardState = GS_NO;
2656 		}
2657 		switch (condResult) {
2658 		case CR_FALSE:	/* May also mean a syntax error. */
2659 			if (!SkipIrrelevantBranches())
2660 				return NULL;
2661 			continue;
2662 		case CR_TRUE:
2663 			continue;
2664 		case CR_ERROR:	/* Not a conditional line */
2665 			if (ParseForLoop(line))
2666 				continue;
2667 			break;
2668 		}
2669 		return line;
2670 	}
2671 }
2672 
2673 static void
2674 FinishDependencyGroup(void)
2675 {
2676 	GNodeListNode *ln;
2677 
2678 	if (targets == NULL)
2679 		return;
2680 
2681 	for (ln = targets->first; ln != NULL; ln = ln->next) {
2682 		GNode *gn = ln->datum;
2683 
2684 		Suff_EndTransform(gn);
2685 
2686 		/*
2687 		 * Mark the target as already having commands if it does, to
2688 		 * keep from having shell commands on multiple dependency
2689 		 * lines.
2690 		 */
2691 		if (!Lst_IsEmpty(&gn->commands))
2692 			gn->type |= OP_HAS_COMMANDS;
2693 	}
2694 
2695 	Lst_Free(targets);
2696 	targets = NULL;
2697 }
2698 
2699 /* Add the command to each target from the current dependency spec. */
2700 static void
2701 ParseLine_ShellCommand(const char *p)
2702 {
2703 	cpp_skip_whitespace(&p);
2704 	if (*p == '\0')
2705 		return;		/* skip empty commands */
2706 
2707 	if (targets == NULL) {
2708 		Parse_Error(PARSE_FATAL,
2709 		    "Unassociated shell command \"%s\"", p);
2710 		return;
2711 	}
2712 
2713 	{
2714 		char *cmd = bmake_strdup(p);
2715 		GNodeListNode *ln;
2716 
2717 		for (ln = targets->first; ln != NULL; ln = ln->next) {
2718 			GNode *gn = ln->datum;
2719 			GNode_AddCommand(gn, cmd);
2720 		}
2721 #ifdef CLEANUP
2722 		Lst_Append(&targCmds, cmd);
2723 #endif
2724 	}
2725 }
2726 
2727 static void
2728 HandleBreak(const char *arg)
2729 {
2730 	IncludedFile *curFile = CurFile();
2731 
2732 	if (arg[0] != '\0')
2733 		Parse_Error(PARSE_FATAL,
2734 		    "The .break directive does not take arguments");
2735 
2736 	if (curFile->forLoop != NULL) {
2737 		/* pretend we reached EOF */
2738 		For_Break(curFile->forLoop);
2739 		cond_depth = CurFile_CondMinDepth();
2740 		ParseEOF();
2741 	} else
2742 		Parse_Error(PARSE_FATAL, "break outside of for loop");
2743 }
2744 
2745 /*
2746  * See if the line starts with one of the known directives, and if so, handle
2747  * the directive.
2748  */
2749 static bool
2750 ParseDirective(char *line)
2751 {
2752 	char *p = line + 1;
2753 	const char *arg;
2754 	Substring dir;
2755 
2756 	pp_skip_whitespace(&p);
2757 	if (IsInclude(p, false)) {
2758 		ParseInclude(p);
2759 		return true;
2760 	}
2761 
2762 	dir.start = p;
2763 	while (ch_islower(*p) || *p == '-')
2764 		p++;
2765 	dir.end = p;
2766 
2767 	if (*p != '\0' && !ch_isspace(*p))
2768 		return false;
2769 
2770 	pp_skip_whitespace(&p);
2771 	arg = p;
2772 
2773 	if (Substring_Equals(dir, "break"))
2774 		HandleBreak(arg);
2775 	else if (Substring_Equals(dir, "undef"))
2776 		Var_Undef(arg);
2777 	else if (Substring_Equals(dir, "export"))
2778 		Var_Export(VEM_PLAIN, arg);
2779 	else if (Substring_Equals(dir, "export-env"))
2780 		Var_Export(VEM_ENV, arg);
2781 	else if (Substring_Equals(dir, "export-literal"))
2782 		Var_Export(VEM_LITERAL, arg);
2783 	else if (Substring_Equals(dir, "unexport"))
2784 		Var_UnExport(false, arg);
2785 	else if (Substring_Equals(dir, "unexport-env"))
2786 		Var_UnExport(true, arg);
2787 	else if (Substring_Equals(dir, "info"))
2788 		HandleMessage(PARSE_INFO, "info", arg);
2789 	else if (Substring_Equals(dir, "warning"))
2790 		HandleMessage(PARSE_WARNING, "warning", arg);
2791 	else if (Substring_Equals(dir, "error"))
2792 		HandleMessage(PARSE_FATAL, "error", arg);
2793 	else
2794 		return false;
2795 	return true;
2796 }
2797 
2798 bool
2799 Parse_VarAssign(const char *line, bool finishDependencyGroup, GNode *scope)
2800 {
2801 	VarAssign var;
2802 
2803 	if (!Parse_IsVar(line, &var))
2804 		return false;
2805 	if (finishDependencyGroup)
2806 		FinishDependencyGroup();
2807 	Parse_Var(&var, scope);
2808 	free(var.varname);
2809 	return true;
2810 }
2811 
2812 void
2813 Parse_GuardElse(void)
2814 {
2815 	IncludedFile *curFile = CurFile();
2816 	if (cond_depth == curFile->condMinDepth + 1)
2817 		curFile->guardState = GS_NO;
2818 }
2819 
2820 void
2821 Parse_GuardEndif(void)
2822 {
2823 	IncludedFile *curFile = CurFile();
2824 	if (cond_depth == curFile->condMinDepth
2825 	    && curFile->guardState == GS_COND)
2826 		curFile->guardState = GS_DONE;
2827 }
2828 
2829 static char *
2830 FindSemicolon(char *p)
2831 {
2832 	int depth = 0;
2833 
2834 	for (; *p != '\0'; p++) {
2835 		if (*p == '\\' && p[1] != '\0') {
2836 			p++;
2837 			continue;
2838 		}
2839 
2840 		if (*p == '$' && (p[1] == '(' || p[1] == '{'))
2841 			depth++;
2842 		else if (depth > 0 && (*p == ')' || *p == '}'))
2843 			depth--;
2844 		else if (depth == 0 && *p == ';')
2845 			break;
2846 	}
2847 	return p;
2848 }
2849 
2850 static void
2851 ParseDependencyLine(char *line)
2852 {
2853 	VarEvalMode emode;
2854 	char *expanded_line;
2855 	const char *shellcmd = NULL;
2856 
2857 	{
2858 		char *semicolon = FindSemicolon(line);
2859 		if (*semicolon != '\0') {
2860 			/* Terminate the dependency list at the ';' */
2861 			*semicolon = '\0';
2862 			shellcmd = semicolon + 1;
2863 		}
2864 	}
2865 
2866 	/*
2867 	 * We now know it's a dependency line, so it needs to have all
2868 	 * variables expanded before being parsed.
2869 	 *
2870 	 * XXX: Ideally the dependency line would first be split into
2871 	 * its left-hand side, dependency operator and right-hand side,
2872 	 * and then each side would be expanded on its own.  This would
2873 	 * allow for the left-hand side to allow only defined variables
2874 	 * and to allow variables on the right-hand side to be undefined
2875 	 * as well.
2876 	 *
2877 	 * Parsing the line first would also prevent that targets
2878 	 * generated from expressions are interpreted as the
2879 	 * dependency operator, such as in "target${:U\:} middle: source",
2880 	 * in which the middle is interpreted as a source, not a target.
2881 	 */
2882 
2883 	/*
2884 	 * In lint mode, allow undefined variables to appear in dependency
2885 	 * lines.
2886 	 *
2887 	 * Ideally, only the right-hand side would allow undefined variables
2888 	 * since it is common to have optional dependencies. Having undefined
2889 	 * variables on the left-hand side is more unusual though.  Since
2890 	 * both sides are expanded in a single pass, there is not much choice
2891 	 * what to do here.
2892 	 *
2893 	 * In normal mode, it does not matter whether undefined variables are
2894 	 * allowed or not since as of 2020-09-14, Var_Parse does not print
2895 	 * any parse errors in such a case. It simply returns the special
2896 	 * empty string var_Error, which cannot be detected in the result of
2897 	 * Var_Subst.
2898 	 */
2899 	emode = opts.strict ? VARE_WANTRES : VARE_UNDEFERR;
2900 	expanded_line = Var_Subst(line, SCOPE_CMDLINE, emode);
2901 	/* TODO: handle errors */
2902 
2903 	/* Need a fresh list for the target nodes */
2904 	if (targets != NULL)
2905 		Lst_Free(targets);
2906 	targets = Lst_New();
2907 
2908 	ParseDependency(expanded_line, line);
2909 	free(expanded_line);
2910 
2911 	if (shellcmd != NULL)
2912 		ParseLine_ShellCommand(shellcmd);
2913 }
2914 
2915 static void
2916 ParseLine(char *line)
2917 {
2918 	if (line[0] == '.' && ParseDirective(line))
2919 		return;
2920 
2921 	if (line[0] == '\t') {
2922 		ParseLine_ShellCommand(line + 1);
2923 		return;
2924 	}
2925 
2926 #ifdef SYSVINCLUDE
2927 	if (IsSysVInclude(line)) {
2928 		ParseTraditionalInclude(line);
2929 		return;
2930 	}
2931 #endif
2932 
2933 #ifdef GMAKEEXPORT
2934 	if (strncmp(line, "export", 6) == 0 && ch_isspace(line[6]) &&
2935 	    strchr(line, ':') == NULL) {
2936 		ParseGmakeExport(line);
2937 		return;
2938 	}
2939 #endif
2940 
2941 	if (Parse_VarAssign(line, true, SCOPE_GLOBAL))
2942 		return;
2943 
2944 	FinishDependencyGroup();
2945 
2946 	ParseDependencyLine(line);
2947 }
2948 
2949 /* Interpret a top-level makefile. */
2950 void
2951 Parse_File(const char *name, int fd)
2952 {
2953 	char *line;
2954 	Buffer buf;
2955 
2956 	buf = LoadFile(name, fd != -1 ? fd : STDIN_FILENO);
2957 	if (fd != -1)
2958 		(void)close(fd);
2959 
2960 	assert(targets == NULL);
2961 
2962 	Parse_PushInput(name, 1, 0, buf, NULL);
2963 
2964 	do {
2965 		while ((line = ReadHighLevelLine()) != NULL) {
2966 			DEBUG2(PARSE, "Parsing line %u: %s\n",
2967 			    CurFile()->lineno, line);
2968 			ParseLine(line);
2969 		}
2970 	} while (ParseEOF());
2971 
2972 	FinishDependencyGroup();
2973 
2974 	if (parseErrors != 0) {
2975 		(void)fflush(stdout);
2976 		(void)fprintf(stderr,
2977 		    "%s: Fatal errors encountered -- cannot continue\n",
2978 		    progname);
2979 		PrintOnError(NULL, "");
2980 		exit(1);
2981 	}
2982 }
2983 
2984 /* Initialize the parsing module. */
2985 void
2986 Parse_Init(void)
2987 {
2988 	mainNode = NULL;
2989 	parseIncPath = SearchPath_New();
2990 	sysIncPath = SearchPath_New();
2991 	defSysIncPath = SearchPath_New();
2992 	Vector_Init(&includes, sizeof(IncludedFile));
2993 	HashTable_Init(&guards);
2994 }
2995 
2996 /* Clean up the parsing module. */
2997 void
2998 Parse_End(void)
2999 {
3000 #ifdef CLEANUP
3001 	HashIter hi;
3002 
3003 	Lst_DoneCall(&targCmds, free);
3004 	assert(targets == NULL);
3005 	SearchPath_Free(defSysIncPath);
3006 	SearchPath_Free(sysIncPath);
3007 	SearchPath_Free(parseIncPath);
3008 	assert(includes.len == 0);
3009 	Vector_Done(&includes);
3010 	HashIter_Init(&hi, &guards);
3011 	while (HashIter_Next(&hi) != NULL) {
3012 		Guard *guard = hi.entry->value;
3013 		free(guard->name);
3014 		free(guard);
3015 	}
3016 	HashTable_Done(&guards);
3017 #endif
3018 }
3019 
3020 
3021 /* Populate the list with the single main target to create, or error out. */
3022 void
3023 Parse_MainName(GNodeList *mainList)
3024 {
3025 	if (mainNode == NULL)
3026 		Punt("no target to make.");
3027 
3028 	Lst_Append(mainList, mainNode);
3029 	if (mainNode->type & OP_DOUBLEDEP)
3030 		Lst_AppendAll(mainList, &mainNode->cohorts);
3031 
3032 	Global_Append(".TARGETS", mainNode->name);
3033 }
3034 
3035 int
3036 Parse_NumErrors(void)
3037 {
3038 	return parseErrors;
3039 }
3040