xref: /freebsd/contrib/bmake/parse.c (revision 34a3834eadd03bec7703b8fbf9123f27b1114986)
1 /*	$NetBSD: parse.c,v 1.755 2026/02/10 18:53:34 sjg Exp $	*/
2 
3 /*
4  * Copyright (c) 1988, 1989, 1990, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Adam de Boor.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 /*
36  * Copyright (c) 1989 by Berkeley Softworks
37  * All rights reserved.
38  *
39  * This code is derived from software contributed to Berkeley by
40  * Adam de Boor.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  * 3. All advertising materials mentioning features or use of this software
51  *    must display the following acknowledgement:
52  *	This product includes software developed by the University of
53  *	California, Berkeley and its contributors.
54  * 4. Neither the name of the University nor the names of its contributors
55  *    may be used to endorse or promote products derived from this software
56  *    without specific prior written permission.
57  *
58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68  * SUCH DAMAGE.
69  */
70 
71 /*
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.755 2026/02/10 18:53:34 sjg 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(FILE * f,bool includingInnermost)484 PrintStackTrace(FILE *f, bool includingInnermost)
485 {
486 	char *stackTrace = GetStackTrace(includingInnermost);
487 	fprintf(f, "%s", stackTrace);
488 	fflush(f);
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(f, 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 /* Append the command to the target node. */
1989 static void
GNode_AddCommand(GNode * gn,char * cmd)1990 GNode_AddCommand(GNode *gn, char *cmd)
1991 {
1992 	if ((gn->type & OP_DOUBLEDEP) && gn->cohorts.last != NULL)
1993 		gn = gn->cohorts.last->datum;
1994 
1995 	/* if target already supplied, ignore commands */
1996 	if (!(gn->type & OP_HAS_COMMANDS)) {
1997 		Lst_Append(&gn->commands, cmd);
1998 		RememberLocation(gn);
1999 	} else {
2000 		Parse_Error(PARSE_WARNING,
2001 		    "duplicate script for target \"%s\" ignored",
2002 		    gn->name);
2003 		ParseErrorInternal(gn, PARSE_WARNING,
2004 		    "using previous script for \"%s\" defined here",
2005 		    gn->name);
2006 	}
2007 }
2008 
2009 /*
2010  * Parse a directive like '.include' or '.-include'.
2011  *
2012  * .include "user-makefile.mk"
2013  * .include <system-makefile.mk>
2014  */
2015 static void
ParseInclude(char * directive)2016 ParseInclude(char *directive)
2017 {
2018 	char endc;		/* '>' or '"' */
2019 	char *p;
2020 	bool silent = directive[0] != 'i';
2021 	FStr file;
2022 
2023 	p = directive + (silent ? 8 : 7);
2024 	pp_skip_hspace(&p);
2025 
2026 	if (*p != '"' && *p != '<') {
2027 		Parse_Error(PARSE_FATAL,
2028 		    ".include filename must be delimited by \"\" or <>");
2029 		return;
2030 	}
2031 
2032 	endc = *p++ == '<' ? '>' : '"';
2033 	file = FStr_InitRefer(p);
2034 
2035 	while (*p != '\0' && *p != endc)
2036 		p++;
2037 
2038 	if (*p != endc) {
2039 		Parse_Error(PARSE_FATAL,
2040 		    "Unclosed .include filename, \"%c\" expected", endc);
2041 		return;
2042 	}
2043 
2044 	*p = '\0';
2045 
2046 	Var_Expand(&file, SCOPE_CMDLINE, VARE_EVAL);
2047 	IncludeFile(file.str, endc == '>', directive[0] == 'd', silent);
2048 	FStr_Done(&file);
2049 }
2050 
2051 /*
2052  * Split filename into dirname + basename, then assign these to the
2053  * given variables.
2054  */
2055 static void
SetFilenameVars(const char * filename,const char * dirvar,const char * filevar)2056 SetFilenameVars(const char *filename, const char *dirvar, const char *filevar)
2057 {
2058 	const char *slash, *basename;
2059 	FStr dirname;
2060 
2061 	slash = strrchr(filename, '/');
2062 	if (slash == NULL) {
2063 		dirname = FStr_InitRefer(curdir);
2064 		basename = filename;
2065 	} else {
2066 		dirname = FStr_InitOwn(bmake_strsedup(filename, slash));
2067 		basename = slash + 1;
2068 	}
2069 
2070 	Global_Set(dirvar, dirname.str);
2071 	Global_Set(filevar, basename);
2072 
2073 	DEBUG4(PARSE, "SetFilenameVars: ${%s} = `%s' ${%s} = `%s'\n",
2074 	    dirvar, dirname.str, filevar, basename);
2075 	FStr_Done(&dirname);
2076 }
2077 
2078 /*
2079  * Return the immediately including file.
2080  *
2081  * This is made complicated since the .for loop is implemented as a special
2082  * kind of .include; see For_Run.
2083  */
2084 static const char *
GetActuallyIncludingFile(void)2085 GetActuallyIncludingFile(void)
2086 {
2087 	size_t i;
2088 	const IncludedFile *incs = GetInclude(0);
2089 
2090 	for (i = includes.len; i >= 2; i--)
2091 		if (incs[i - 1].forLoop == NULL)
2092 			return incs[i - 2].name.str;
2093 	return NULL;
2094 }
2095 
2096 /* Set .PARSEDIR, .PARSEFILE, .INCLUDEDFROMDIR and .INCLUDEDFROMFILE. */
2097 static void
SetParseFile(const char * filename)2098 SetParseFile(const char *filename)
2099 {
2100 	const char *including;
2101 
2102 	SetFilenameVars(filename, ".PARSEDIR", ".PARSEFILE");
2103 
2104 	including = GetActuallyIncludingFile();
2105 	if (including != NULL) {
2106 		SetFilenameVars(including,
2107 		    ".INCLUDEDFROMDIR", ".INCLUDEDFROMFILE");
2108 	} else {
2109 		Global_Delete(".INCLUDEDFROMDIR");
2110 		Global_Delete(".INCLUDEDFROMFILE");
2111 	}
2112 }
2113 
2114 static bool
StrContainsWord(const char * str,const char * word)2115 StrContainsWord(const char *str, const char *word)
2116 {
2117 	size_t strLen = strlen(str);
2118 	size_t wordLen = strlen(word);
2119 	const char *p;
2120 
2121 	if (strLen < wordLen)
2122 		return false;
2123 
2124 	for (p = str; p != NULL; p = strchr(p, ' ')) {
2125 		if (*p == ' ')
2126 			p++;
2127 		if (p > str + strLen - wordLen)
2128 			return false;
2129 
2130 		if (memcmp(p, word, wordLen) == 0 &&
2131 		    (p[wordLen] == '\0' || p[wordLen] == ' '))
2132 			return true;
2133 	}
2134 	return false;
2135 }
2136 
2137 /*
2138  * XXX: Searching through a set of words with this linear search is
2139  * inefficient for variables that contain thousands of words.
2140  *
2141  * XXX: The paths in this list don't seem to be normalized in any way.
2142  */
2143 static bool
VarContainsWord(const char * varname,const char * word)2144 VarContainsWord(const char *varname, const char *word)
2145 {
2146 	FStr val = Var_Value(SCOPE_GLOBAL, varname);
2147 	bool found = val.str != NULL && StrContainsWord(val.str, word);
2148 	FStr_Done(&val);
2149 	return found;
2150 }
2151 
2152 /*
2153  * Track the makefiles we read - so makefiles can set dependencies on them.
2154  * Avoid adding anything more than once.
2155  *
2156  * Time complexity: O(n) per call, in total O(n^2), where n is the number
2157  * of makefiles that have been loaded.
2158  */
2159 static void
TrackInput(const char * name)2160 TrackInput(const char *name)
2161 {
2162 	if (!VarContainsWord(".MAKE.MAKEFILES", name))
2163 		Global_Append(".MAKE.MAKEFILES", name);
2164 }
2165 
2166 
2167 /* Parse from the given buffer, later return to the current file. */
2168 void
Parse_PushInput(const char * name,unsigned lineno,unsigned readLines,Buffer buf,struct ForLoop * forLoop)2169 Parse_PushInput(const char *name, unsigned lineno, unsigned readLines,
2170 		Buffer buf, struct ForLoop *forLoop)
2171 {
2172 	IncludedFile *curFile;
2173 
2174 	if (forLoop != NULL)
2175 		name = CurFile()->name.str;
2176 	else
2177 		TrackInput(name);
2178 
2179 	DEBUG3(PARSE, "Parse_PushInput: %s%s:%u\n",
2180 	    forLoop != NULL ? ".for loop in ": "", name, lineno);
2181 
2182 	curFile = Vector_Push(&includes);
2183 	curFile->name = FStr_InitOwn(bmake_strdup(name));
2184 	curFile->lineno = lineno;
2185 	curFile->readLines = readLines;
2186 	curFile->forHeadLineno = lineno;
2187 	curFile->forBodyReadLines = readLines;
2188 	curFile->buf = buf;
2189 	curFile->depending = doing_depend;	/* restore this on EOF */
2190 	curFile->guardState = forLoop == NULL ? GS_START : GS_NO;
2191 	curFile->guard = NULL;
2192 	curFile->forLoop = forLoop;
2193 
2194 	if (forLoop != NULL && !For_NextIteration(forLoop, &curFile->buf))
2195 		abort();	/* see For_Run */
2196 
2197 	curFile->buf_ptr = curFile->buf.data;
2198 	curFile->buf_end = curFile->buf.data + curFile->buf.len;
2199 	curFile->condMinDepth = cond_depth;
2200 	SetParseFile(name);
2201 }
2202 
2203 /* Check if the directive is an include directive. */
2204 static bool
IsInclude(const char * dir,bool sysv)2205 IsInclude(const char *dir, bool sysv)
2206 {
2207 	if (dir[0] == 's' || dir[0] == '-' || (dir[0] == 'd' && !sysv))
2208 		dir++;
2209 
2210 	if (strncmp(dir, "include", 7) != 0)
2211 		return false;
2212 
2213 	/* Space is not mandatory for BSD .include */
2214 	return !sysv || ch_isspace(dir[7]);
2215 }
2216 
2217 
2218 /* Check if the line is a SYSV include directive. */
2219 static bool
IsSysVInclude(const char * line)2220 IsSysVInclude(const char *line)
2221 {
2222 	const char *p;
2223 
2224 	if (!IsInclude(line, true))
2225 		return false;
2226 
2227 	/* Avoid interpreting a dependency line as an include */
2228 	for (p = line; (p = strchr(p, ':')) != NULL;) {
2229 
2230 		/* end of line -> it's a dependency */
2231 		if (*++p == '\0')
2232 			return false;
2233 
2234 		/* '::' operator or ': ' -> it's a dependency */
2235 		if (*p == ':' || ch_isspace(*p))
2236 			return false;
2237 	}
2238 	return true;
2239 }
2240 
2241 /* Push to another file.  The line points to the word "include". */
2242 static void
ParseTraditionalInclude(char * line)2243 ParseTraditionalInclude(char *line)
2244 {
2245 	char *p;		/* current position in file spec */
2246 	bool done = false;
2247 	bool silent = line[0] != 'i';
2248 	char *file = line + (silent ? 8 : 7);
2249 	char *all_files;
2250 
2251 	DEBUG1(PARSE, "ParseTraditionalInclude: %s\n", file);
2252 
2253 	pp_skip_whitespace(&file);
2254 
2255 	all_files = Var_Subst(file, SCOPE_CMDLINE, VARE_EVAL);
2256 	/* TODO: handle errors */
2257 
2258 	for (file = all_files; !done; file = p + 1) {
2259 		/* Skip to end of line or next whitespace */
2260 		for (p = file; *p != '\0' && !ch_isspace(*p); p++)
2261 			continue;
2262 
2263 		if (*p != '\0')
2264 			*p = '\0';
2265 		else
2266 			done = true;
2267 
2268 		IncludeFile(file, false, false, silent);
2269 	}
2270 
2271 	free(all_files);
2272 }
2273 
2274 /* Parse "export <variable>=<value>", and actually export it. */
2275 static void
ParseGmakeExport(char * line)2276 ParseGmakeExport(char *line)
2277 {
2278 	char *variable = line + 6;
2279 	char *value;
2280 
2281 	DEBUG1(PARSE, "ParseGmakeExport: %s\n", variable);
2282 
2283 	pp_skip_whitespace(&variable);
2284 
2285 	for (value = variable; *value != '\0' && *value != '='; value++)
2286 		continue;
2287 
2288 	if (*value != '=') {
2289 		Parse_Error(PARSE_FATAL,
2290 		    "Variable/Value missing from \"export\"");
2291 		return;
2292 	}
2293 	*value++ = '\0';	/* terminate variable */
2294 
2295 	/*
2296 	 * Expand the value before putting it in the environment.
2297 	 */
2298 	value = Var_Subst(value, SCOPE_CMDLINE, VARE_EVAL);
2299 	/* TODO: handle errors */
2300 
2301 	setenv(variable, value, 1);
2302 	free(value);
2303 }
2304 
2305 /*
2306  * When the end of the current file or .for loop is reached, continue reading
2307  * the previous file at the previous location.
2308  *
2309  * Results:
2310  *	true to continue parsing, i.e. it had only reached the end of an
2311  *	included file, false if the main file has been parsed completely.
2312  */
2313 static bool
ParseEOF(void)2314 ParseEOF(void)
2315 {
2316 	IncludedFile *curFile = CurFile();
2317 
2318 	doing_depend = curFile->depending;
2319 	if (curFile->forLoop != NULL &&
2320 	    For_NextIteration(curFile->forLoop, &curFile->buf)) {
2321 		curFile->buf_ptr = curFile->buf.data;
2322 		curFile->buf_end = curFile->buf.data + curFile->buf.len;
2323 		curFile->readLines = curFile->forBodyReadLines;
2324 		return true;
2325 	}
2326 
2327 	Cond_EndFile();
2328 
2329 	if (curFile->guardState == GS_DONE) {
2330 		HashEntry *he = HashTable_CreateEntry(&guards,
2331 		    curFile->name.str, NULL);
2332 		if (he->value != NULL) {
2333 			free(((Guard *)he->value)->name);
2334 			free(he->value);
2335 		}
2336 		HashEntry_Set(he, curFile->guard);
2337 	} else if (curFile->guard != NULL) {
2338 		free(curFile->guard->name);
2339 		free(curFile->guard);
2340 	}
2341 
2342 	FStr_Done(&curFile->name);
2343 	Buf_Done(&curFile->buf);
2344 	if (curFile->forLoop != NULL)
2345 		ForLoop_Free(curFile->forLoop);
2346 	Vector_Pop(&includes);
2347 
2348 	if (includes.len == 0) {
2349 		/* We've run out of input */
2350 		Global_Delete(".PARSEDIR");
2351 		Global_Delete(".PARSEFILE");
2352 		Global_Delete(".INCLUDEDFROMDIR");
2353 		Global_Delete(".INCLUDEDFROMFILE");
2354 		return false;
2355 	}
2356 
2357 	curFile = CurFile();
2358 	DEBUG2(PARSE, "ParseEOF: returning to %s:%u\n",
2359 	    curFile->name.str, curFile->readLines + 1);
2360 
2361 	SetParseFile(curFile->name.str);
2362 	return true;
2363 }
2364 
2365 typedef enum ParseRawLineResult {
2366 	PRLR_LINE,
2367 	PRLR_EOF,
2368 	PRLR_ERROR
2369 } ParseRawLineResult;
2370 
2371 /*
2372  * Parse until the end of a line, taking into account lines that end with
2373  * backslash-newline.  The resulting line goes from out_line to out_line_end;
2374  * the line is not null-terminated.
2375  */
2376 static ParseRawLineResult
ParseRawLine(IncludedFile * curFile,char ** out_line,char ** out_line_end,char ** out_firstBackslash,char ** out_commentLineEnd)2377 ParseRawLine(IncludedFile *curFile, char **out_line, char **out_line_end,
2378 	     char **out_firstBackslash, char **out_commentLineEnd)
2379 {
2380 	char *line = curFile->buf_ptr;
2381 	char *buf_end = curFile->buf_end;
2382 	char *p = line;
2383 	char *line_end = line;
2384 	char *firstBackslash = NULL;
2385 	char *commentLineEnd = NULL;
2386 	ParseRawLineResult res = PRLR_LINE;
2387 
2388 	curFile->readLines++;
2389 
2390 	for (;;) {
2391 		char ch;
2392 
2393 		if (p == buf_end) {
2394 			res = PRLR_EOF;
2395 			break;
2396 		}
2397 
2398 		ch = *p;
2399 		if (ch == '\0' || (ch == '\\' && p[1] == '\0')) {
2400 			Parse_Error(PARSE_FATAL, "Zero byte read from file");
2401 			exit(2);
2402 		}
2403 
2404 		/* Treat next character after '\' as literal. */
2405 		if (ch == '\\') {
2406 			if (firstBackslash == NULL)
2407 				firstBackslash = p;
2408 			if (p[1] == '\n') {
2409 				curFile->readLines++;
2410 				if (p + 2 == buf_end) {
2411 					line_end = p;
2412 					*line_end = '\n';
2413 					p += 2;
2414 					continue;
2415 				}
2416 			}
2417 			p += 2;
2418 			line_end = p;
2419 			assert(p <= buf_end);
2420 			continue;
2421 		}
2422 
2423 		/*
2424 		 * Remember the first '#' for comment stripping, unless
2425 		 * the previous char was '[', as in the modifier ':[#]'.
2426 		 */
2427 		if (ch == '#' && commentLineEnd == NULL &&
2428 		    !(p > line && p[-1] == '['))
2429 			commentLineEnd = line_end;
2430 
2431 		p++;
2432 		if (ch == '\n')
2433 			break;
2434 
2435 		/* We are not interested in trailing whitespace. */
2436 		if (!ch_isspace(ch))
2437 			line_end = p;
2438 	}
2439 
2440 	curFile->buf_ptr = p;
2441 	*out_line = line;
2442 	*out_line_end = line_end;
2443 	*out_firstBackslash = firstBackslash;
2444 	*out_commentLineEnd = commentLineEnd;
2445 	return res;
2446 }
2447 
2448 /*
2449  * Beginning at start, unescape '\#' to '#' and replace backslash-newline
2450  * with a single space.
2451  */
2452 static void
UnescapeBackslash(char * line,char * start)2453 UnescapeBackslash(char *line, char *start)
2454 {
2455 	const char *src = start;
2456 	char *dst = start;
2457 	char *spaceStart = line;
2458 
2459 	for (;;) {
2460 		char ch = *src++;
2461 		if (ch != '\\') {
2462 			if (ch == '\0')
2463 				break;
2464 			*dst++ = ch;
2465 			continue;
2466 		}
2467 
2468 		ch = *src++;
2469 		if (ch == '\0') {
2470 			/* Delete '\\' at the end of the buffer. */
2471 			dst--;
2472 			break;
2473 		}
2474 
2475 		/* Delete '\\' from before '#' on non-command lines. */
2476 		if (ch == '#' && line[0] != '\t')
2477 			*dst++ = ch;
2478 		else if (ch == '\n') {
2479 			cpp_skip_hspace(&src);
2480 			*dst++ = ' ';
2481 		} else {
2482 			/* Leave '\\' in the buffer for later. */
2483 			*dst++ = '\\';
2484 			*dst++ = ch;
2485 			/* Keep an escaped ' ' at the line end. */
2486 			spaceStart = dst;
2487 		}
2488 	}
2489 
2490 	/* Delete any trailing spaces - eg from empty continuations */
2491 	while (dst > spaceStart && ch_isspace(dst[-1]))
2492 		dst--;
2493 	*dst = '\0';
2494 }
2495 
2496 typedef enum LineKind {
2497 	/*
2498 	 * Return the next line that is neither empty nor a comment.
2499 	 * Backslash line continuations are folded into a single space.
2500 	 * A trailing comment, if any, is discarded.
2501 	 */
2502 	LK_NONEMPTY,
2503 
2504 	/*
2505 	 * Return the next line, even if it is empty or a comment.
2506 	 * Preserve backslash-newline to keep the line numbers correct.
2507 	 *
2508 	 * Used in .for loops to collect the body of the loop while waiting
2509 	 * for the corresponding .endfor.
2510 	 */
2511 	LK_FOR_BODY,
2512 
2513 	/*
2514 	 * Return the next line that starts with a dot.
2515 	 * Backslash line continuations are folded into a single space.
2516 	 * A trailing comment, if any, is discarded.
2517 	 *
2518 	 * Used in .if directives to skip over irrelevant branches while
2519 	 * waiting for the corresponding .endif.
2520 	 */
2521 	LK_DOT
2522 } LineKind;
2523 
2524 /*
2525  * Return the next "interesting" logical line from the current file.  The
2526  * returned string will be freed at the end of including the file.
2527  */
2528 static char *
ReadLowLevelLine(LineKind kind)2529 ReadLowLevelLine(LineKind kind)
2530 {
2531 	IncludedFile *curFile = CurFile();
2532 	ParseRawLineResult res;
2533 	char *line;
2534 	char *line_end;
2535 	char *firstBackslash;
2536 	char *commentLineEnd;
2537 
2538 	for (;;) {
2539 		curFile->lineno = curFile->readLines + 1;
2540 		res = ParseRawLine(curFile,
2541 		    &line, &line_end, &firstBackslash, &commentLineEnd);
2542 		if (res == PRLR_ERROR)
2543 			return NULL;
2544 
2545 		if (line == line_end || line == commentLineEnd) {
2546 			if (res == PRLR_EOF)
2547 				return NULL;
2548 			if (kind != LK_FOR_BODY)
2549 				continue;
2550 		}
2551 
2552 		/* We now have a line of data */
2553 		assert(ch_isspace(*line_end));
2554 		*line_end = '\0';
2555 
2556 		if (kind == LK_FOR_BODY)
2557 			return line;	/* Don't join the physical lines. */
2558 
2559 		if (kind == LK_DOT && line[0] != '.')
2560 			continue;
2561 		break;
2562 	}
2563 
2564 	if (commentLineEnd != NULL && line[0] != '\t')
2565 		*commentLineEnd = '\0';
2566 	if (firstBackslash != NULL)
2567 		UnescapeBackslash(line, firstBackslash);
2568 	return line;
2569 }
2570 
2571 static bool
SkipIrrelevantBranches(void)2572 SkipIrrelevantBranches(void)
2573 {
2574 	const char *line;
2575 
2576 	while ((line = ReadLowLevelLine(LK_DOT)) != NULL)
2577 		if (Cond_EvalLine(line) == CR_TRUE)
2578 			return true;
2579 	return false;
2580 }
2581 
2582 static bool
ParseForLoop(const char * line)2583 ParseForLoop(const char *line)
2584 {
2585 	int rval;
2586 	unsigned forHeadLineno;
2587 	unsigned bodyReadLines;
2588 	int forLevel;
2589 
2590 	rval = For_Eval(line);
2591 	if (rval == 0)
2592 		return false;	/* Not a .for line */
2593 	if (rval < 0)
2594 		return true;	/* Syntax error - error printed, ignore line */
2595 
2596 	forHeadLineno = CurFile()->lineno;
2597 	bodyReadLines = CurFile()->readLines;
2598 
2599 	/* Accumulate the loop body until the matching '.endfor'. */
2600 	forLevel = 1;
2601 	do {
2602 		line = ReadLowLevelLine(LK_FOR_BODY);
2603 		if (line == NULL) {
2604 			Parse_Error(PARSE_FATAL,
2605 			    "Unexpected end of file in .for loop");
2606 			break;
2607 		}
2608 	} while (For_Accum(line, &forLevel));
2609 
2610 	For_Run(forHeadLineno, bodyReadLines);
2611 	return true;
2612 }
2613 
2614 /*
2615  * Read an entire line from the input file.
2616  *
2617  * Empty lines, .if and .for are handled by this function, while variable
2618  * assignments, other directives, dependency lines and shell commands are
2619  * handled by the caller.
2620  *
2621  * Return a line without trailing whitespace, or NULL for EOF.  The returned
2622  * string will be freed at the end of including the file.
2623  */
2624 static char *
ReadHighLevelLine(void)2625 ReadHighLevelLine(void)
2626 {
2627 	char *line;
2628 	CondResult condResult;
2629 
2630 	for (;;) {
2631 		IncludedFile *curFile = CurFile();
2632 		line = ReadLowLevelLine(LK_NONEMPTY);
2633 		if (posix_state == PS_MAYBE_NEXT_LINE)
2634 			posix_state = PS_NOW_OR_NEVER;
2635 		else if (posix_state != PS_SET)
2636 			posix_state = PS_TOO_LATE;
2637 		if (line == NULL)
2638 			return NULL;
2639 
2640 		DEBUG3(PARSE, "Parsing %s:%u: %s\n",
2641 		    curFile->name.str, curFile->lineno, line);
2642 		if (curFile->guardState != GS_NO
2643 		    && ((curFile->guardState == GS_START && line[0] != '.')
2644 			|| curFile->guardState == GS_DONE))
2645 			curFile->guardState = GS_NO;
2646 		if (line[0] != '.')
2647 			return line;
2648 
2649 		condResult = Cond_EvalLine(line);
2650 		if (curFile->guardState == GS_START) {
2651 			Guard *guard;
2652 			if (condResult != CR_ERROR
2653 			    && (guard = Cond_ExtractGuard(line)) != NULL) {
2654 				curFile->guardState = GS_COND;
2655 				curFile->guard = guard;
2656 			} else
2657 				curFile->guardState = GS_NO;
2658 		}
2659 		switch (condResult) {
2660 		case CR_FALSE:	/* May also mean a syntax error. */
2661 			if (!SkipIrrelevantBranches())
2662 				return NULL;
2663 			continue;
2664 		case CR_TRUE:
2665 			continue;
2666 		case CR_ERROR:	/* Not a conditional line */
2667 			if (ParseForLoop(line))
2668 				continue;
2669 			break;
2670 		}
2671 		return line;
2672 	}
2673 }
2674 
2675 static void
FinishDependencyGroup(void)2676 FinishDependencyGroup(void)
2677 {
2678 	GNodeListNode *ln;
2679 
2680 	if (targets == NULL)
2681 		return;
2682 
2683 	for (ln = targets->first; ln != NULL; ln = ln->next) {
2684 		GNode *gn = ln->datum;
2685 
2686 		Suff_EndTransform(gn);
2687 
2688 		/*
2689 		 * Mark the target as already having commands if it does, to
2690 		 * keep from having shell commands on multiple dependency
2691 		 * lines.
2692 		 */
2693 		if (!Lst_IsEmpty(&gn->commands))
2694 			gn->type |= OP_HAS_COMMANDS;
2695 	}
2696 
2697 	Lst_Free(targets);
2698 	targets = NULL;
2699 }
2700 
2701 #ifdef CLEANUP
Parse_RegisterCommand(char * cmd)2702 void Parse_RegisterCommand(char *cmd)
2703 {
2704 	Lst_Append(&targCmds, cmd);
2705 }
2706 #endif
2707 
2708 /* Add the command to each target from the current dependency spec. */
2709 static void
ParseLine_ShellCommand(const char * p)2710 ParseLine_ShellCommand(const char *p)
2711 {
2712 	cpp_skip_whitespace(&p);
2713 	if (*p == '\0')
2714 		return;		/* skip empty commands */
2715 
2716 	if (targets == NULL) {
2717 		Parse_Error(PARSE_FATAL,
2718 		    "Unassociated shell command \"%s\"", p);
2719 		return;
2720 	}
2721 
2722 	{
2723 		char *cmd = bmake_strdup(p);
2724 		GNodeListNode *ln;
2725 
2726 		for (ln = targets->first; ln != NULL; ln = ln->next) {
2727 			GNode *gn = ln->datum;
2728 			GNode_AddCommand(gn, cmd);
2729 		}
2730 		Parse_RegisterCommand(cmd);
2731 	}
2732 }
2733 
2734 static void
HandleBreak(const char * arg)2735 HandleBreak(const char *arg)
2736 {
2737 	IncludedFile *curFile = CurFile();
2738 
2739 	if (arg[0] != '\0')
2740 		Parse_Error(PARSE_FATAL,
2741 		    "The .break directive does not take arguments");
2742 
2743 	if (curFile->forLoop != NULL) {
2744 		/* pretend we reached EOF */
2745 		For_Break(curFile->forLoop);
2746 		cond_depth = CurFile_CondMinDepth();
2747 		ParseEOF();
2748 	} else
2749 		Parse_Error(PARSE_FATAL, "break outside of for loop");
2750 }
2751 
2752 /*
2753  * See if the line starts with one of the known directives, and if so, handle
2754  * the directive.
2755  */
2756 static bool
ParseDirective(char * line)2757 ParseDirective(char *line)
2758 {
2759 	char *p = line + 1;
2760 	const char *arg;
2761 	Substring dir;
2762 
2763 	pp_skip_whitespace(&p);
2764 	if (IsInclude(p, false)) {
2765 		ParseInclude(p);
2766 		return true;
2767 	}
2768 
2769 	dir.start = p;
2770 	while (ch_islower(*p) || *p == '-')
2771 		p++;
2772 	dir.end = p;
2773 
2774 	if (*p != '\0' && !ch_isspace(*p))
2775 		return false;
2776 
2777 	pp_skip_whitespace(&p);
2778 	arg = p;
2779 
2780 	if (Substring_Equals(dir, "break"))
2781 		HandleBreak(arg);
2782 	else if (Substring_Equals(dir, "undef"))
2783 		Var_Undef(arg);
2784 	else if (Substring_Equals(dir, "export"))
2785 		Var_Export(VEM_PLAIN, arg);
2786 	else if (Substring_Equals(dir, "export-all"))
2787 		Var_Export(VEM_ALL, arg);
2788 	else if (Substring_Equals(dir, "export-env"))
2789 		Var_Export(VEM_ENV, arg);
2790 	else if (Substring_Equals(dir, "export-literal"))
2791 		Var_Export(VEM_LITERAL, arg);
2792 	else if (Substring_Equals(dir, "unexport"))
2793 		Var_UnExport(false, arg);
2794 	else if (Substring_Equals(dir, "unexport-env"))
2795 		Var_UnExport(true, arg);
2796 	else if (Substring_Equals(dir, "info"))
2797 		HandleMessage(PARSE_INFO, "info", arg);
2798 	else if (Substring_Equals(dir, "warning"))
2799 		HandleMessage(PARSE_WARNING, "warning", arg);
2800 	else if (Substring_Equals(dir, "error"))
2801 		HandleMessage(PARSE_FATAL, "error", arg);
2802 	else
2803 		return false;
2804 	return true;
2805 }
2806 
2807 bool
Parse_VarAssign(const char * line,bool finishDependencyGroup,GNode * scope)2808 Parse_VarAssign(const char *line, bool finishDependencyGroup, GNode *scope)
2809 {
2810 	VarAssign var;
2811 
2812 	if (!Parse_IsVar(line, &var))
2813 		return false;
2814 	if (finishDependencyGroup)
2815 		FinishDependencyGroup();
2816 	Parse_Var(&var, scope);
2817 	free(var.varname);
2818 	return true;
2819 }
2820 
2821 void
Parse_GuardElse(void)2822 Parse_GuardElse(void)
2823 {
2824 	IncludedFile *curFile = CurFile();
2825 	if (cond_depth == curFile->condMinDepth + 1)
2826 		curFile->guardState = GS_NO;
2827 }
2828 
2829 void
Parse_GuardEndif(void)2830 Parse_GuardEndif(void)
2831 {
2832 	IncludedFile *curFile = CurFile();
2833 	if (cond_depth == curFile->condMinDepth
2834 	    && curFile->guardState == GS_COND)
2835 		curFile->guardState = GS_DONE;
2836 }
2837 
2838 static char *
FindSemicolon(char * p)2839 FindSemicolon(char *p)
2840 {
2841 	int depth = 0;
2842 
2843 	for (; *p != '\0'; p++) {
2844 		if (*p == '\\' && p[1] != '\0') {
2845 			p++;
2846 			continue;
2847 		}
2848 
2849 		if (*p == '$' && (p[1] == '(' || p[1] == '{'))
2850 			depth++;
2851 		else if (depth > 0 && (*p == ')' || *p == '}'))
2852 			depth--;
2853 		else if (depth == 0 && *p == ';')
2854 			break;
2855 	}
2856 	return p;
2857 }
2858 
2859 static void
ParseDependencyLine(char * line)2860 ParseDependencyLine(char *line)
2861 {
2862 	char *expanded_line;
2863 	const char *shellcmd = NULL;
2864 
2865 	{
2866 		char *semicolon = FindSemicolon(line);
2867 		if (*semicolon != '\0') {
2868 			/* Terminate the dependency list at the ';' */
2869 			*semicolon = '\0';
2870 			shellcmd = semicolon + 1;
2871 		}
2872 	}
2873 
2874 	expanded_line = Var_Subst(line, SCOPE_CMDLINE, VARE_EVAL);
2875 	/* TODO: handle errors */
2876 
2877 	/* Need a fresh list for the target nodes */
2878 	if (targets != NULL)
2879 		Lst_Free(targets);
2880 	targets = Lst_New();
2881 
2882 	ParseDependency(expanded_line, line);
2883 	free(expanded_line);
2884 
2885 	if (shellcmd != NULL)
2886 		ParseLine_ShellCommand(shellcmd);
2887 }
2888 
2889 static void
ParseLine(char * line)2890 ParseLine(char *line)
2891 {
2892 	if (line[0] == '.' && ParseDirective(line))
2893 		return;
2894 
2895 	if (line[0] == '\t') {
2896 		ParseLine_ShellCommand(line + 1);
2897 		return;
2898 	}
2899 
2900 	if (IsSysVInclude(line)) {
2901 		ParseTraditionalInclude(line);
2902 		return;
2903 	}
2904 
2905 	if (strncmp(line, "export", 6) == 0 && ch_isspace(line[6]) &&
2906 	    strchr(line, ':') == NULL) {
2907 		ParseGmakeExport(line);
2908 		return;
2909 	}
2910 
2911 	if (Parse_VarAssign(line, true, SCOPE_GLOBAL))
2912 		return;
2913 
2914 	FinishDependencyGroup();
2915 
2916 	ParseDependencyLine(line);
2917 }
2918 
2919 /* Interpret a top-level makefile. */
2920 void
Parse_File(const char * name,int fd)2921 Parse_File(const char *name, int fd)
2922 {
2923 	char *line;
2924 	Buffer buf;
2925 
2926 	buf = LoadFile(name, fd != -1 ? fd : STDIN_FILENO);
2927 	if (fd != -1)
2928 		(void)close(fd);
2929 
2930 	assert(targets == NULL);
2931 
2932 	Parse_PushInput(name, 1, 0, buf, NULL);
2933 
2934 	do {
2935 		while ((line = ReadHighLevelLine()) != NULL) {
2936 			ParseLine(line);
2937 		}
2938 	} while (ParseEOF());
2939 
2940 	FinishDependencyGroup();
2941 
2942 	if (parseErrors != 0) {
2943 		(void)fflush(stdout);
2944 		(void)fprintf(stderr,
2945 		    "%s: Fatal errors encountered -- cannot continue\n",
2946 		    progname);
2947 		PrintOnError(NULL, "");
2948 		exit(1);
2949 	}
2950 }
2951 
2952 /* Initialize the parsing module. */
2953 void
Parse_Init(void)2954 Parse_Init(void)
2955 {
2956 	mainNode = NULL;
2957 	parseIncPath = SearchPath_New();
2958 	sysIncPath = SearchPath_New();
2959 	defSysIncPath = SearchPath_New();
2960 	Vector_Init(&includes, sizeof(IncludedFile));
2961 	HashTable_Init(&guards);
2962 }
2963 
2964 #ifdef CLEANUP
2965 /* Clean up the parsing module. */
2966 void
Parse_End(void)2967 Parse_End(void)
2968 {
2969 	HashIter hi;
2970 
2971 	Lst_DoneFree(&targCmds);
2972 	assert(targets == NULL);
2973 	SearchPath_Free(defSysIncPath);
2974 	SearchPath_Free(sysIncPath);
2975 	SearchPath_Free(parseIncPath);
2976 	assert(includes.len == 0);
2977 	Vector_Done(&includes);
2978 	HashIter_Init(&hi, &guards);
2979 	while (HashIter_Next(&hi)) {
2980 		Guard *guard = hi.entry->value;
2981 		free(guard->name);
2982 		free(guard);
2983 	}
2984 	HashTable_Done(&guards);
2985 }
2986 #endif
2987 
2988 
2989 /* Populate the list with the single main target to create, or error out. */
2990 void
Parse_MainName(GNodeList * mainList)2991 Parse_MainName(GNodeList *mainList)
2992 {
2993 	if (mainNode == NULL)
2994 		Punt("no target to make.");
2995 
2996 	Lst_Append(mainList, mainNode);
2997 	if (mainNode->type & OP_DOUBLEDEP)
2998 		Lst_AppendAll(mainList, &mainNode->cohorts);
2999 
3000 	Global_Append(".TARGETS", mainNode->name);
3001 }
3002