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