xref: /freebsd/contrib/bmake/main.c (revision d9a65c5de1c9f30ae71ce0be8fb88be9d20d216d)
1 /*	$NetBSD: main.c,v 1.639 2025/03/07 06:50:34 rillig Exp $	*/
2 
3 /*
4  * Copyright (c) 1988, 1989, 1990, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Adam de Boor.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 /*
36  * Copyright (c) 1989 by Berkeley Softworks
37  * All rights reserved.
38  *
39  * This code is derived from software contributed to Berkeley by
40  * Adam de Boor.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  * 3. All advertising materials mentioning features or use of this software
51  *    must display the following acknowledgement:
52  *	This product includes software developed by the University of
53  *	California, Berkeley and its contributors.
54  * 4. Neither the name of the University nor the names of its contributors
55  *    may be used to endorse or promote products derived from this software
56  *    without specific prior written permission.
57  *
58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68  * SUCH DAMAGE.
69  */
70 
71 /*
72  * The main file for this entire program. Exit routines etc. reside here.
73  *
74  * Utility functions defined in this file:
75  *
76  *	Main_ParseArgLine
77  *			Parse and process command line arguments from a
78  *			single string.  Used to implement the special targets
79  *			.MFLAGS and .MAKEFLAGS.
80  *
81  *	Error		Print a tagged error message.
82  *
83  *	Fatal		Print an error message and exit.
84  *
85  *	Punt		Abort all jobs and exit with a message.
86  */
87 
88 #include <sys/types.h>
89 #include <sys/time.h>
90 #include <sys/param.h>
91 #include <sys/resource.h>
92 #include <sys/stat.h>
93 #if defined(MAKE_NATIVE) && defined(HAVE_SYSCTL)
94 #include <sys/sysctl.h>
95 #endif
96 #include <sys/utsname.h>
97 #include "wait.h"
98 
99 #include <errno.h>
100 #include <signal.h>
101 #include <stdarg.h>
102 #include <time.h>
103 
104 #include "make.h"
105 #include "dir.h"
106 #include "job.h"
107 #include "pathnames.h"
108 #include "trace.h"
109 
110 /*	"@(#)main.c	8.3 (Berkeley) 3/19/94"	*/
111 MAKE_RCSID("$NetBSD: main.c,v 1.639 2025/03/07 06:50:34 rillig Exp $");
112 #if defined(MAKE_NATIVE)
113 __COPYRIGHT("@(#) Copyright (c) 1988, 1989, 1990, 1993 "
114 	    "The Regents of the University of California.  "
115 	    "All rights reserved.");
116 #endif
117 
118 #ifndef __arraycount
119 # define __arraycount(__x)	(sizeof(__x) / sizeof(__x[0]))
120 #endif
121 
122 CmdOpts opts;
123 time_t now;			/* Time at start of make */
124 GNode *defaultNode;		/* .DEFAULT node */
125 bool allPrecious;		/* .PRECIOUS given on a line by itself */
126 bool deleteOnError;		/* .DELETE_ON_ERROR: set */
127 
128 static int maxJobTokens;	/* -j argument */
129 static bool enterFlagObj;	/* -w and objdir != srcdir */
130 
131 static int jp_0 = -1, jp_1 = -1; /* ends of parent job pipe */
132 bool doing_depend;		/* Set while reading .depend */
133 static bool jobsRunning;	/* true if the jobs might be running */
134 static const char *tracefile;
135 static bool ReadMakefile(const char *);
136 static void purge_relative_cached_realpaths(void);
137 
138 static bool ignorePWD;		/* if we use -C, PWD is meaningless */
139 static char objdir[MAXPATHLEN + 1]; /* where we chdir'ed to */
140 char curdir[MAXPATHLEN + 1];	/* Startup directory */
141 const char *progname;
142 char *makeDependfile;
143 pid_t myPid;
144 int makelevel;
145 
146 bool forceJobs = false;
147 static int main_errors = 0;
148 static HashTable cached_realpaths;
149 
150 /*
151  * For compatibility with the POSIX version of MAKEFLAGS that includes
152  * all the options without '-', convert 'flags' to '-f -l -a -g -s '.
153  */
154 static char *
155 explode(const char *flags)
156 {
157 	char *exploded, *ep;
158 	const char *p;
159 
160 	if (flags == NULL)
161 		return NULL;
162 
163 	for (p = flags; *p != '\0'; p++)
164 		if (!ch_isalpha(*p))
165 			return bmake_strdup(flags);
166 
167 	exploded = bmake_malloc((size_t)(p - flags) * 3 + 1);
168 	for (p = flags, ep = exploded; *p != '\0'; p++) {
169 		*ep++ = '-';
170 		*ep++ = *p;
171 		*ep++ = ' ';
172 	}
173 	*ep = '\0';
174 	return exploded;
175 }
176 
177 MAKE_ATTR_DEAD static void
178 usage(void)
179 {
180 	size_t prognameLen = strcspn(progname, "[");
181 
182 	(void)fprintf(stderr,
183 "usage: %.*s [-BeikNnqrSstWwX]\n"
184 "            [-C directory] [-D variable] [-d flags] [-f makefile]\n"
185 "            [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n"
186 "            [-V variable] [-v variable] [variable=value] [target ...]\n",
187 	    (int)prognameLen, progname);
188 	exit(2);
189 }
190 
191 static void
192 MainParseArgDebugFile(const char *arg)
193 {
194 	const char *mode;
195 	size_t len;
196 	char *fname;
197 
198 	if (opts.debug_file != stdout && opts.debug_file != stderr)
199 		fclose(opts.debug_file);
200 
201 	if (*arg == '+') {
202 		arg++;
203 		mode = "a";
204 	} else
205 		mode = "w";
206 
207 	if (strcmp(arg, "stdout") == 0) {
208 		opts.debug_file = stdout;
209 		return;
210 	}
211 	if (strcmp(arg, "stderr") == 0) {
212 		opts.debug_file = stderr;
213 		return;
214 	}
215 
216 	len = strlen(arg);
217 	fname = bmake_malloc(len + 20);
218 	memcpy(fname, arg, len + 1);
219 
220 	/* Replace the trailing '%d' after '.%d' with the pid. */
221 	if (len >= 3 && memcmp(fname + len - 3, ".%d", 3) == 0)
222 		snprintf(fname + len - 2, 20, "%d", getpid());
223 
224 	opts.debug_file = fopen(fname, mode);
225 	if (opts.debug_file == NULL) {
226 		fprintf(stderr, "Cannot open debug file \"%s\"\n", fname);
227 		exit(2);
228 	}
229 	free(fname);
230 }
231 
232 static void
233 MainParseArgDebug(const char *argvalue)
234 {
235 	const char *modules;
236 	DebugFlags debug = opts.debug;
237 
238 	for (modules = argvalue; *modules != '\0'; modules++) {
239 		switch (*modules) {
240 		case '0':	/* undocumented, only intended for tests */
241 			memset(&debug, 0, sizeof(debug));
242 			break;
243 		case 'A':
244 			memset(&debug, ~0, sizeof(debug));
245 			break;
246 		case 'a':
247 			debug.DEBUG_ARCH = true;
248 			break;
249 		case 'C':
250 			debug.DEBUG_CWD = true;
251 			break;
252 		case 'c':
253 			debug.DEBUG_COND = true;
254 			break;
255 		case 'd':
256 			debug.DEBUG_DIR = true;
257 			break;
258 		case 'e':
259 			debug.DEBUG_ERROR = true;
260 			break;
261 		case 'f':
262 			debug.DEBUG_FOR = true;
263 			break;
264 		case 'g':
265 			if (modules[1] == '1') {
266 				debug.DEBUG_GRAPH1 = true;
267 				modules++;
268 			} else if (modules[1] == '2') {
269 				debug.DEBUG_GRAPH2 = true;
270 				modules++;
271 			} else if (modules[1] == '3') {
272 				debug.DEBUG_GRAPH3 = true;
273 				modules++;
274 			}
275 			break;
276 		case 'h':
277 			debug.DEBUG_HASH = true;
278 			break;
279 		case 'j':
280 			debug.DEBUG_JOB = true;
281 			break;
282 		case 'L':
283 			opts.strict = true;
284 			break;
285 		case 'l':
286 			debug.DEBUG_LOUD = true;
287 			break;
288 		case 'M':
289 			debug.DEBUG_META = true;
290 			break;
291 		case 'm':
292 			debug.DEBUG_MAKE = true;
293 			break;
294 		case 'n':
295 			debug.DEBUG_SCRIPT = true;
296 			break;
297 		case 'p':
298 			debug.DEBUG_PARSE = true;
299 			break;
300 		case 's':
301 			debug.DEBUG_SUFF = true;
302 			break;
303 		case 't':
304 			debug.DEBUG_TARG = true;
305 			break;
306 		case 'V':
307 			opts.debugVflag = true;
308 			break;
309 		case 'v':
310 			debug.DEBUG_VAR = true;
311 			break;
312 		case 'x':
313 			debug.DEBUG_SHELL = true;
314 			break;
315 		case 'F':
316 			MainParseArgDebugFile(modules + 1);
317 			goto finish;
318 		default:
319 			(void)fprintf(stderr,
320 			    "%s: illegal argument to d option -- %c\n",
321 			    progname, *modules);
322 			usage();
323 		}
324 	}
325 
326 finish:
327 	opts.debug = debug;
328 
329 	setvbuf(opts.debug_file, NULL, _IONBF, 0);
330 	if (opts.debug_file != stdout)
331 		setvbuf(stdout, NULL, _IOLBF, 0);
332 }
333 
334 /* Is path relative or does it contain any relative component "." or ".."? */
335 static bool
336 IsRelativePath(const char *path)
337 {
338 	const char *p;
339 
340 	if (path[0] != '/')
341 		return true;
342 	p = path;
343 	while ((p = strstr(p, "/.")) != NULL) {
344 		p += 2;
345 		if (*p == '.')
346 			p++;
347 		if (*p == '/' || *p == '\0')
348 			return true;
349 	}
350 	return false;
351 }
352 
353 static void
354 MainParseArgChdir(const char *argvalue)
355 {
356 	struct stat sa, sb;
357 
358 	if (chdir(argvalue) == -1) {
359 		(void)fprintf(stderr, "%s: chdir %s: %s\n",
360 		    progname, argvalue, strerror(errno));
361 		exit(2);	/* Not 1 so -q can distinguish error */
362 	}
363 	if (getcwd(curdir, MAXPATHLEN) == NULL) {
364 		(void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
365 		exit(2);
366 	}
367 	if (!IsRelativePath(argvalue) &&
368 	    stat(argvalue, &sa) != -1 &&
369 	    stat(curdir, &sb) != -1 &&
370 	    sa.st_ino == sb.st_ino &&
371 	    sa.st_dev == sb.st_dev)
372 		snprintf(curdir, MAXPATHLEN, "%s", argvalue);
373 	ignorePWD = true;
374 }
375 
376 static void
377 MainParseArgJobsInternal(const char *argvalue)
378 {
379 	char end;
380 	if (sscanf(argvalue, "%d,%d%c", &jp_0, &jp_1, &end) != 2) {
381 		(void)fprintf(stderr,
382 		    "%s: internal error -- J option malformed (%s)\n",
383 		    progname, argvalue);
384 		usage();
385 	}
386 	if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
387 	    (fcntl(jp_1, F_GETFD, 0) < 0)) {
388 		jp_0 = -1;
389 		jp_1 = -1;
390 		opts.compatMake = true;
391 	} else {
392 		Global_Append(MAKEFLAGS, "-J");
393 		Global_Append(MAKEFLAGS, argvalue);
394 	}
395 }
396 
397 static void
398 MainParseArgJobs(const char *arg)
399 {
400 	const char *p;
401 	char *end;
402 	char v[12];
403 
404 	forceJobs = true;
405 	opts.maxJobs = (int)strtol(arg, &end, 0);
406 	p = end;
407 #ifdef _SC_NPROCESSORS_ONLN
408 	if (*p != '\0') {
409 		double d;
410 
411 		if (*p == 'C')
412 			d = (opts.maxJobs > 0) ? opts.maxJobs : 1;
413 		else if (*p == '.') {
414 			d = strtod(arg, &end);
415 			p = end;
416 		} else
417 			d = 0.0;
418 		if (d > 0.0) {
419 			p = "";
420 			opts.maxJobs = (int)sysconf(_SC_NPROCESSORS_ONLN);
421 			opts.maxJobs = (int)(d * (double)opts.maxJobs);
422 		}
423 	}
424 #endif
425 	if (*p != '\0' || opts.maxJobs < 1) {
426 		(void)fprintf(stderr,
427 		    "%s: argument '%s' to option '-j' "
428 		    "must be a positive number\n",
429 		    progname, arg);
430 		exit(2);	/* Not 1 so -q can distinguish error */
431 	}
432 	snprintf(v, sizeof(v), "%d", opts.maxJobs);
433 	Global_Append(MAKEFLAGS, "-j");
434 	Global_Append(MAKEFLAGS, v);
435 	Global_Set(".MAKE.JOBS", v);
436 	maxJobTokens = opts.maxJobs;
437 }
438 
439 static void
440 MainParseArgSysInc(const char *argvalue)
441 {
442 	if (strncmp(argvalue, ".../", 4) == 0) {
443 		char *found_path = Dir_FindHereOrAbove(curdir, argvalue + 4);
444 		if (found_path == NULL)
445 			return;
446 		(void)SearchPath_Add(sysIncPath, found_path);
447 		free(found_path);
448 	} else {
449 		(void)SearchPath_Add(sysIncPath, argvalue);
450 	}
451 	Global_Append(MAKEFLAGS, "-m");
452 	Global_Append(MAKEFLAGS, argvalue);
453 	Dir_SetSYSPATH();
454 }
455 
456 static bool
457 MainParseOption(char c, const char *argvalue)
458 {
459 	switch (c) {
460 	case '\0':
461 		break;
462 	case 'B':
463 		opts.compatMake = true;
464 		Global_Append(MAKEFLAGS, "-B");
465 		Global_Set(".MAKE.MODE", "compat");
466 		break;
467 	case 'C':
468 		MainParseArgChdir(argvalue);
469 		break;
470 	case 'D':
471 		if (argvalue[0] == '\0')
472 			return false;
473 		Var_SetExpand(SCOPE_GLOBAL, argvalue, "1");
474 		Global_Append(MAKEFLAGS, "-D");
475 		Global_Append(MAKEFLAGS, argvalue);
476 		break;
477 	case 'I':
478 		SearchPath_Add(parseIncPath, argvalue);
479 		Global_Append(MAKEFLAGS, "-I");
480 		Global_Append(MAKEFLAGS, argvalue);
481 		break;
482 	case 'J':
483 		MainParseArgJobsInternal(argvalue);
484 		break;
485 	case 'N':
486 		opts.noExecute = true;
487 		opts.noRecursiveExecute = true;
488 		Global_Append(MAKEFLAGS, "-N");
489 		break;
490 	case 'S':
491 		opts.keepgoing = false;
492 		Global_Append(MAKEFLAGS, "-S");
493 		break;
494 	case 'T':
495 		tracefile = bmake_strdup(argvalue);
496 		Global_Append(MAKEFLAGS, "-T");
497 		Global_Append(MAKEFLAGS, argvalue);
498 		break;
499 	case 'V':
500 	case 'v':
501 		opts.printVars = c == 'v' ? PVM_EXPANDED : PVM_UNEXPANDED;
502 		Lst_Append(&opts.variables, bmake_strdup(argvalue));
503 		/* XXX: Why always -V? */
504 		Global_Append(MAKEFLAGS, "-V");
505 		Global_Append(MAKEFLAGS, argvalue);
506 		break;
507 	case 'W':
508 		opts.parseWarnFatal = true;
509 		/* XXX: why no Global_Append? */
510 		break;
511 	case 'X':
512 		opts.varNoExportEnv = true;
513 		Global_Append(MAKEFLAGS, "-X");
514 		break;
515 	case 'd':
516 		/* If '-d-opts' don't pass to children */
517 		if (argvalue[0] == '-')
518 			argvalue++;
519 		else {
520 			Global_Append(MAKEFLAGS, "-d");
521 			Global_Append(MAKEFLAGS, argvalue);
522 		}
523 		MainParseArgDebug(argvalue);
524 		break;
525 	case 'e':
526 		opts.checkEnvFirst = true;
527 		Global_Append(MAKEFLAGS, "-e");
528 		break;
529 	case 'f':
530 		Lst_Append(&opts.makefiles, bmake_strdup(argvalue));
531 		break;
532 	case 'i':
533 		opts.ignoreErrors = true;
534 		Global_Append(MAKEFLAGS, "-i");
535 		break;
536 	case 'j':
537 		MainParseArgJobs(argvalue);
538 		break;
539 	case 'k':
540 		opts.keepgoing = true;
541 		Global_Append(MAKEFLAGS, "-k");
542 		break;
543 	case 'm':
544 		MainParseArgSysInc(argvalue);
545 		/* XXX: why no Var_Append? */
546 		break;
547 	case 'n':
548 		opts.noExecute = true;
549 		Global_Append(MAKEFLAGS, "-n");
550 		break;
551 	case 'q':
552 		opts.query = true;
553 		/* Kind of nonsensical, wot? */
554 		Global_Append(MAKEFLAGS, "-q");
555 		break;
556 	case 'r':
557 		opts.noBuiltins = true;
558 		Global_Append(MAKEFLAGS, "-r");
559 		break;
560 	case 's':
561 		opts.silent = true;
562 		Global_Append(MAKEFLAGS, "-s");
563 		break;
564 	case 't':
565 		opts.touch = true;
566 		Global_Append(MAKEFLAGS, "-t");
567 		break;
568 	case 'w':
569 		opts.enterFlag = true;
570 		Global_Append(MAKEFLAGS, "-w");
571 		break;
572 	default:
573 		usage();
574 	}
575 	return true;
576 }
577 
578 /*
579  * Parse the given arguments.  Called from main() and from
580  * Main_ParseArgLine() when the .MAKEFLAGS target is used.
581  *
582  * The arguments must be treated as read-only and will be freed after the
583  * call.
584  *
585  * XXX: Deal with command line overriding .MAKEFLAGS in makefile
586  */
587 static void
588 MainParseArgs(int argc, char **argv)
589 {
590 	char c;
591 	int arginc;
592 	char *argvalue;
593 	char *optscan;
594 	bool inOption, dashDash = false;
595 
596 	const char *optspecs = "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrstv:w";
597 /* Can't actually use getopt(3) because rescanning is not portable */
598 
599 rearg:
600 	inOption = false;
601 	optscan = NULL;
602 	while (argc > 1) {
603 		const char *optspec;
604 		if (!inOption)
605 			optscan = argv[1];
606 		c = *optscan++;
607 		arginc = 0;
608 		if (inOption) {
609 			if (c == '\0') {
610 				argv++;
611 				argc--;
612 				inOption = false;
613 				continue;
614 			}
615 		} else {
616 			if (c != '-' || dashDash)
617 				break;
618 			inOption = true;
619 			c = *optscan++;
620 		}
621 		/* '-' found at some earlier point */
622 		optspec = strchr(optspecs, c);
623 		if (c != '\0' && optspec != NULL && optspec[1] == ':') {
624 			/*
625 			 * -<something> found, and <something> should have an
626 			 * argument
627 			 */
628 			inOption = false;
629 			arginc = 1;
630 			argvalue = optscan;
631 			if (*argvalue == '\0') {
632 				if (argc < 3)
633 					goto noarg;
634 				argvalue = argv[2];
635 				arginc = 2;
636 			}
637 		} else {
638 			argvalue = NULL;
639 		}
640 		switch (c) {
641 		case '\0':
642 			arginc = 1;
643 			inOption = false;
644 			break;
645 		case '-':
646 			dashDash = true;
647 			break;
648 		default:
649 			if (!MainParseOption(c, argvalue))
650 				goto noarg;
651 		}
652 		argv += arginc;
653 		argc -= arginc;
654 	}
655 
656 	/*
657 	 * See if the rest of the arguments are variable assignments and
658 	 * perform them if so. Else take them to be targets and stuff them
659 	 * on the end of the "create" list.
660 	 */
661 	for (; argc > 1; argv++, argc--) {
662 		if (!Parse_VarAssign(argv[1], false, SCOPE_CMDLINE)) {
663 			if (argv[1][0] == '\0')
664 				Punt("illegal (null) argument.");
665 			if (argv[1][0] == '-' && !dashDash)
666 				goto rearg;
667 			Lst_Append(&opts.create, bmake_strdup(argv[1]));
668 		}
669 	}
670 
671 	return;
672 noarg:
673 	(void)fprintf(stderr, "%s: option requires an argument -- %c\n",
674 	    progname, c);
675 	usage();
676 }
677 
678 /*
679  * Break a line of arguments into words and parse them.
680  *
681  * Used when a .MFLAGS or .MAKEFLAGS target is encountered during parsing and
682  * by main() when reading the MAKEFLAGS environment variable.
683  */
684 void
685 Main_ParseArgLine(const char *line)
686 {
687 	Words words;
688 	char *buf;
689 	const char *p;
690 
691 	if (line == NULL)
692 		return;
693 	for (p = line; *p == ' '; p++)
694 		continue;
695 	if (p[0] == '\0')
696 		return;
697 
698 	{
699 		FStr argv0 = Var_Value(SCOPE_GLOBAL, ".MAKE");
700 		buf = str_concat3(argv0.str, " ", p);
701 		FStr_Done(&argv0);
702 	}
703 
704 	words = Str_Words(buf, true);
705 	if (words.words == NULL) {
706 		Error("Unterminated quoted string [%s]", buf);
707 		free(buf);
708 		return;
709 	}
710 	free(buf);
711 	MainParseArgs((int)words.len, words.words);
712 
713 	Words_Free(words);
714 }
715 
716 bool
717 Main_SetObjdir(bool writable, const char *fmt, ...)
718 {
719 	struct stat sb;
720 	char *path;
721 	char buf[MAXPATHLEN + 1];
722 	char buf2[MAXPATHLEN + 1];
723 	va_list ap;
724 
725 	va_start(ap, fmt);
726 	vsnprintf(path = buf, MAXPATHLEN, fmt, ap);
727 	va_end(ap);
728 
729 	if (path[0] != '/') {
730 		if (snprintf(buf2, MAXPATHLEN, "%s/%s", curdir, path) <= MAXPATHLEN)
731 			path = buf2;
732 		else
733 			return false;
734 	}
735 
736 	/* look for the directory and try to chdir there */
737 	if (stat(path, &sb) != 0 || !S_ISDIR(sb.st_mode))
738 		return false;
739 
740 	if ((writable && access(path, W_OK) != 0) || chdir(path) != 0) {
741 		(void)fprintf(stderr, "%s: warning: %s: %s.\n",
742 		    progname, path, strerror(errno));
743 		/* Allow debugging how we got here - not always obvious */
744 		if (GetBooleanExpr("${MAKE_DEBUG_OBJDIR_CHECK_WRITABLE}",
745 			false))
746 			PrintOnError(NULL, "");
747 		return false;
748 	}
749 
750 	snprintf(objdir, sizeof objdir, "%s", path);
751 	Global_Set(".OBJDIR", objdir);
752 	setenv("PWD", objdir, 1);
753 	Dir_InitDot();
754 	purge_relative_cached_realpaths();
755 	if (opts.enterFlag && strcmp(objdir, curdir) != 0)
756 		enterFlagObj = true;
757 	return true;
758 }
759 
760 static bool
761 SetVarObjdir(bool writable, const char *var, const char *suffix)
762 {
763 	FStr path = Var_Value(SCOPE_CMDLINE, var);
764 
765 	if (path.str == NULL || path.str[0] == '\0') {
766 		FStr_Done(&path);
767 		return false;
768 	}
769 
770 	Var_Expand(&path, SCOPE_GLOBAL, VARE_EVAL);
771 
772 	(void)Main_SetObjdir(writable, "%s%s", path.str, suffix);
773 
774 	FStr_Done(&path);
775 	return true;
776 }
777 
778 /*
779  * Splits str into words (in-place, modifying it), adding them to the list.
780  * The string must be kept alive as long as the list.
781  */
782 void
783 AppendWords(StringList *lp, char *str)
784 {
785 	char *p;
786 	const char *sep = " \t";
787 
788 	for (p = strtok(str, sep); p != NULL; p = strtok(NULL, sep))
789 		Lst_Append(lp, p);
790 }
791 
792 #ifdef SIGINFO
793 static void
794 siginfo(int signo MAKE_ATTR_UNUSED)
795 {
796 	char dir[MAXPATHLEN];
797 	char str[2 * MAXPATHLEN];
798 	int len;
799 	if (getcwd(dir, sizeof dir) == NULL)
800 		return;
801 	len = snprintf(str, sizeof str, "%s: Working in: %s\n", progname, dir);
802 	if (len > 0)
803 		(void)write(STDERR_FILENO, str, (size_t)len);
804 }
805 #endif
806 
807 /* Allow makefiles some control over the mode we run in. */
808 static void
809 MakeMode(void)
810 {
811 	char *mode = Var_Subst("${.MAKE.MODE:tl}", SCOPE_GLOBAL, VARE_EVAL);
812 	/* TODO: handle errors */
813 
814 	if (mode[0] != '\0') {
815 		if (strstr(mode, "compat") != NULL) {
816 			opts.compatMake = true;
817 			forceJobs = false;
818 		}
819 #if USE_META
820 		if (strstr(mode, "meta") != NULL)
821 			meta_mode_init(mode);
822 #endif
823 		if (strstr(mode, "randomize-targets") != NULL)
824 			opts.randomizeTargets = true;
825 	}
826 
827 	free(mode);
828 }
829 
830 static void
831 PrintVar(const char *varname, bool expandVars)
832 {
833 	if (strchr(varname, '$') != NULL) {
834 		char *evalue = Var_Subst(varname, SCOPE_GLOBAL, VARE_EVAL);
835 		/* TODO: handle errors */
836 		printf("%s\n", evalue);
837 		free(evalue);
838 
839 	} else if (expandVars) {
840 		char *expr = str_concat3("${", varname, "}");
841 		char *evalue = Var_Subst(expr, SCOPE_GLOBAL, VARE_EVAL);
842 		/* TODO: handle errors */
843 		free(expr);
844 		printf("%s\n", evalue);
845 		free(evalue);
846 
847 	} else {
848 		FStr value = Var_Value(SCOPE_GLOBAL, varname);
849 		printf("%s\n", value.str != NULL ? value.str : "");
850 		FStr_Done(&value);
851 	}
852 }
853 
854 /*
855  * Return a bool based on a variable.
856  *
857  * If the knob is not set, return the fallback.
858  * If set, anything that looks or smells like "No", "False", "Off", "0", etc.
859  * is false, otherwise true.
860  */
861 bool
862 GetBooleanExpr(const char *expr, bool fallback)
863 {
864 	char *value;
865 	bool res;
866 
867 	value = Var_Subst(expr, SCOPE_GLOBAL, VARE_EVAL);
868 	/* TODO: handle errors */
869 	res = ParseBoolean(value, fallback);
870 	free(value);
871 	return res;
872 }
873 
874 static void
875 doPrintVars(void)
876 {
877 	StringListNode *ln;
878 	bool expandVars;
879 
880 	if (opts.printVars == PVM_EXPANDED)
881 		expandVars = true;
882 	else if (opts.debugVflag)
883 		expandVars = false;
884 	else
885 		expandVars = GetBooleanExpr("${.MAKE.EXPAND_VARIABLES}",
886 		    false);
887 
888 	for (ln = opts.variables.first; ln != NULL; ln = ln->next) {
889 		const char *varname = ln->datum;
890 		PrintVar(varname, expandVars);
891 	}
892 }
893 
894 static bool
895 runTargets(void)
896 {
897 	GNodeList targs = LST_INIT;	/* target nodes to create */
898 	bool outOfDate;		/* false if all targets up to date */
899 
900 	/*
901 	 * Have now read the entire graph and need to make a list of
902 	 * targets to create. If none was given on the command line,
903 	 * we consult the parsing module to find the main target(s)
904 	 * to create.
905 	 */
906 	if (Lst_IsEmpty(&opts.create))
907 		Parse_MainName(&targs);
908 	else
909 		Targ_FindList(&targs, &opts.create);
910 
911 	if (!opts.compatMake) {
912 		/*
913 		 * Initialize job module before traversing the graph
914 		 * now that any .BEGIN and .END targets have been read.
915 		 * This is done only if the -q flag wasn't given
916 		 * (to prevent the .BEGIN from being executed should
917 		 * it exist).
918 		 */
919 		if (!opts.query) {
920 			Job_Init();
921 			jobsRunning = true;
922 		}
923 
924 		/* Traverse the graph, checking on all the targets */
925 		outOfDate = Make_Run(&targs);
926 	} else {
927 		Compat_MakeAll(&targs);
928 		outOfDate = false;
929 	}
930 	Lst_Done(&targs);	/* Don't free the targets themselves. */
931 	return outOfDate;
932 }
933 
934 /*
935  * Set up the .TARGETS variable to contain the list of targets to be created.
936  * If none specified, make the variable empty for now, the parser will fill
937  * in the default or .MAIN target later.
938  */
939 static void
940 InitVarTargets(void)
941 {
942 	StringListNode *ln;
943 
944 	if (Lst_IsEmpty(&opts.create)) {
945 		Global_Set(".TARGETS", "");
946 		return;
947 	}
948 
949 	for (ln = opts.create.first; ln != NULL; ln = ln->next) {
950 		const char *name = ln->datum;
951 		Global_Append(".TARGETS", name);
952 	}
953 }
954 
955 static void
956 InitRandom(void)
957 {
958 	struct timeval tv;
959 
960 	gettimeofday(&tv, NULL);
961 	srandom((unsigned int)(tv.tv_sec + tv.tv_usec));
962 }
963 
964 static const char *
965 InitVarMachine(const struct utsname *utsname MAKE_ATTR_UNUSED)
966 {
967 #ifdef FORCE_MACHINE
968 	return FORCE_MACHINE;
969 #else
970     	const char *machine = getenv("MACHINE");
971 
972 	if (machine != NULL)
973 		return machine;
974 
975 #if defined(MAKE_NATIVE)
976 	return utsname->machine;
977 #elif defined(MAKE_MACHINE)
978 	return MAKE_MACHINE;
979 #else
980 	return "unknown";
981 #endif
982 #endif
983 }
984 
985 static const char *
986 InitVarMachineArch(void)
987 {
988 #ifdef FORCE_MACHINE_ARCH
989 	return FORCE_MACHINE_ARCH;
990 #else
991 	const char *env = getenv("MACHINE_ARCH");
992 	if (env != NULL)
993 		return env;
994 
995 #if defined(MAKE_NATIVE) && defined(CTL_HW)
996 	{
997 		struct utsname utsname;
998 		static char machine_arch_buf[sizeof utsname.machine];
999 		const int mib[2] = { CTL_HW, HW_MACHINE_ARCH };
1000 		size_t len = sizeof machine_arch_buf;
1001 
1002 		if (sysctl(mib, (unsigned int)__arraycount(mib),
1003 		    machine_arch_buf, &len, NULL, 0) < 0) {
1004 			(void)fprintf(stderr, "%s: sysctl failed (%s).\n",
1005 			    progname, strerror(errno));
1006 			exit(2);
1007 		}
1008 
1009 		return machine_arch_buf;
1010 	}
1011 #elif defined(MACHINE_ARCH)
1012 	return MACHINE_ARCH;
1013 #elif defined(MAKE_MACHINE_ARCH)
1014 	return MAKE_MACHINE_ARCH;
1015 #else
1016 	return "unknown";
1017 #endif
1018 #endif
1019 }
1020 
1021 #ifndef NO_PWD_OVERRIDE
1022 /*
1023  * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
1024  * since the value of curdir can vary depending on how we got
1025  * here.  That is, sitting at a shell prompt (shell that provides $PWD)
1026  * or via subdir.mk, in which case it's likely a shell which does
1027  * not provide it.
1028  *
1029  * So, to stop it breaking this case only, we ignore PWD if
1030  * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains an expression.
1031  */
1032 static void
1033 HandlePWD(const struct stat *curdir_st)
1034 {
1035 	char *pwd;
1036 	FStr makeobjdir;
1037 	struct stat pwd_st;
1038 
1039 	if (ignorePWD || (pwd = getenv("PWD")) == NULL)
1040 		return;
1041 
1042 	if (Var_Exists(SCOPE_CMDLINE, "MAKEOBJDIRPREFIX"))
1043 		return;
1044 
1045 	makeobjdir = Var_Value(SCOPE_CMDLINE, "MAKEOBJDIR");
1046 	if (makeobjdir.str != NULL && strchr(makeobjdir.str, '$') != NULL)
1047 		goto ignore_pwd;
1048 
1049 	if (stat(pwd, &pwd_st) == 0 &&
1050 	    curdir_st->st_ino == pwd_st.st_ino &&
1051 	    curdir_st->st_dev == pwd_st.st_dev)
1052 		snprintf(curdir, MAXPATHLEN, "%s", pwd);
1053 
1054 ignore_pwd:
1055 	FStr_Done(&makeobjdir);
1056 }
1057 #endif
1058 
1059 /*
1060  * Find the .OBJDIR.  If MAKEOBJDIRPREFIX, or failing that, MAKEOBJDIR is set
1061  * in the environment, try only that value and fall back to .CURDIR if it
1062  * does not exist.
1063  *
1064  * Otherwise, try _PATH_OBJDIR.MACHINE-MACHINE_ARCH, _PATH_OBJDIR.MACHINE,
1065  * and finally _PATH_OBJDIRPREFIX`pwd`, in that order.  If none of these
1066  * paths exist, just use .CURDIR.
1067  */
1068 static void
1069 InitObjdir(const char *machine, const char *machine_arch)
1070 {
1071 	bool writable;
1072 
1073 	Dir_InitCur(curdir);
1074 	writable = GetBooleanExpr("${MAKE_OBJDIR_CHECK_WRITABLE}", true);
1075 	(void)Main_SetObjdir(false, "%s", curdir);
1076 
1077 	if (!SetVarObjdir(writable, "MAKEOBJDIRPREFIX", curdir) &&
1078 	    !SetVarObjdir(writable, "MAKEOBJDIR", "") &&
1079 	    !Main_SetObjdir(writable, "%s.%s-%s", _PATH_OBJDIR, machine, machine_arch) &&
1080 	    !Main_SetObjdir(writable, "%s.%s", _PATH_OBJDIR, machine) &&
1081 	    !Main_SetObjdir(writable, "%s", _PATH_OBJDIR))
1082 		(void)Main_SetObjdir(writable, "%s%s", _PATH_OBJDIRPREFIX, curdir);
1083 }
1084 
1085 /* get rid of resource limit on file descriptors */
1086 static void
1087 UnlimitFiles(void)
1088 {
1089 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
1090 	struct rlimit rl;
1091 	if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
1092 	    rl.rlim_cur != rl.rlim_max) {
1093 #ifdef BMAKE_NOFILE_MAX
1094 		if (BMAKE_NOFILE_MAX < rl.rlim_max)
1095 			rl.rlim_cur = BMAKE_NOFILE_MAX;
1096 		else
1097 #endif
1098 		rl.rlim_cur = rl.rlim_max;
1099 		(void)setrlimit(RLIMIT_NOFILE, &rl);
1100 	}
1101 #endif
1102 }
1103 
1104 static void
1105 CmdOpts_Init(void)
1106 {
1107 	opts.compatMake = false;
1108 	memset(&opts.debug, 0, sizeof(opts.debug));
1109 	/* opts.debug_file has already been initialized earlier */
1110 	opts.strict = false;
1111 	opts.debugVflag = false;
1112 	opts.checkEnvFirst = false;
1113 	Lst_Init(&opts.makefiles);
1114 	opts.ignoreErrors = false;	/* Pay attention to non-zero returns */
1115 	opts.maxJobs = 1;
1116 	opts.keepgoing = false;		/* Stop on error */
1117 	opts.noRecursiveExecute = false; /* Execute all .MAKE targets */
1118 	opts.noExecute = false;		/* Execute all commands */
1119 	opts.query = false;
1120 	opts.noBuiltins = false;	/* Read the built-in rules */
1121 	opts.silent = false;		/* Print commands as executed */
1122 	opts.touch = false;
1123 	opts.printVars = PVM_NONE;
1124 	Lst_Init(&opts.variables);
1125 	opts.parseWarnFatal = false;
1126 	opts.enterFlag = false;
1127 	opts.varNoExportEnv = false;
1128 	Lst_Init(&opts.create);
1129 }
1130 
1131 /*
1132  * Initialize MAKE and .MAKE to the path of the executable, so that it can be
1133  * found by execvp(3) and the shells, even after a chdir.
1134  *
1135  * If it's a relative path and contains a '/', resolve it to an absolute path.
1136  * Otherwise keep it as is, assuming it will be found in the PATH.
1137  */
1138 static void
1139 InitVarMake(const char *argv0)
1140 {
1141 	const char *make = argv0;
1142 	char pathbuf[MAXPATHLEN];
1143 
1144 	if (argv0[0] != '/' && strchr(argv0, '/') != NULL) {
1145 		const char *abspath = cached_realpath(argv0, pathbuf);
1146 		struct stat st;
1147 		if (abspath != NULL && abspath[0] == '/' &&
1148 		    stat(make, &st) == 0)
1149 			make = abspath;
1150 	}
1151 
1152 	Global_Set("MAKE", make);
1153 	Global_Set(".MAKE", make);
1154 }
1155 
1156 /*
1157  * Add the directories from the colon-separated syspath to defSysIncPath.
1158  * After returning, the contents of syspath is unspecified.
1159  */
1160 static void
1161 InitDefSysIncPath(char *syspath)
1162 {
1163 	static char defsyspath[] = _PATH_DEFSYSPATH;
1164 	char *start, *p;
1165 
1166 	/*
1167 	 * If no user-supplied system path was given (through the -m option)
1168 	 * add the directories from the DEFSYSPATH (more than one may be given
1169 	 * as dir1:...:dirn) to the system include path.
1170 	 */
1171 	if (syspath == NULL || syspath[0] == '\0')
1172 		syspath = defsyspath;
1173 	else
1174 		syspath = bmake_strdup(syspath);
1175 
1176 	for (start = syspath; *start != '\0'; start = p) {
1177 		for (p = start; *p != '\0' && *p != ':'; p++)
1178 			continue;
1179 		if (*p == ':')
1180 			*p++ = '\0';
1181 
1182 		/* look for magic parent directory search string */
1183 		if (strncmp(start, ".../", 4) == 0) {
1184 			char *dir = Dir_FindHereOrAbove(curdir, start + 4);
1185 			if (dir != NULL) {
1186 				(void)SearchPath_Add(defSysIncPath, dir);
1187 				free(dir);
1188 			}
1189 		} else {
1190 			(void)SearchPath_Add(defSysIncPath, start);
1191 		}
1192 	}
1193 
1194 	if (syspath != defsyspath)
1195 		free(syspath);
1196 }
1197 
1198 static void
1199 ReadBuiltinRules(void)
1200 {
1201 	StringListNode *ln;
1202 	StringList sysMkFiles = LST_INIT;
1203 
1204 	SearchPath_Expand(
1205 	    Lst_IsEmpty(&sysIncPath->dirs) ? defSysIncPath : sysIncPath,
1206 	    _PATH_DEFSYSMK,
1207 	    &sysMkFiles);
1208 	if (Lst_IsEmpty(&sysMkFiles))
1209 		Fatal("%s: no system rules (%s).", progname, _PATH_DEFSYSMK);
1210 
1211 	for (ln = sysMkFiles.first; ln != NULL; ln = ln->next)
1212 		if (ReadMakefile(ln->datum))
1213 			break;
1214 
1215 	if (ln == NULL)
1216 		Fatal("%s: cannot open %s.",
1217 		    progname, (const char *)sysMkFiles.first->datum);
1218 
1219 	Lst_DoneFree(&sysMkFiles);
1220 }
1221 
1222 static void
1223 InitMaxJobs(void)
1224 {
1225 	char *value;
1226 	int n;
1227 
1228 	if (forceJobs || opts.compatMake ||
1229 	    !Var_Exists(SCOPE_GLOBAL, ".MAKE.JOBS"))
1230 		return;
1231 
1232 	value = Var_Subst("${.MAKE.JOBS}", SCOPE_GLOBAL, VARE_EVAL);
1233 	/* TODO: handle errors */
1234 	n = (int)strtol(value, NULL, 0);
1235 	if (n < 1) {
1236 		(void)fprintf(stderr,
1237 		    "%s: illegal value for .MAKE.JOBS "
1238 		    "-- must be positive integer!\n",
1239 		    progname);
1240 		exit(2);	/* Not 1 so -q can distinguish error */
1241 	}
1242 
1243 	if (n != opts.maxJobs) {
1244 		Global_Append(MAKEFLAGS, "-j");
1245 		Global_Append(MAKEFLAGS, value);
1246 	}
1247 
1248 	opts.maxJobs = n;
1249 	maxJobTokens = opts.maxJobs;
1250 	forceJobs = true;
1251 	free(value);
1252 }
1253 
1254 /*
1255  * For compatibility, look at the directories in the VPATH variable
1256  * and add them to the search path, if the variable is defined. The
1257  * variable's value is in the same format as the PATH environment
1258  * variable, i.e. <directory>:<directory>:<directory>...
1259  */
1260 static void
1261 InitVpath(void)
1262 {
1263 	char *vpath, savec, *path;
1264 	if (!Var_Exists(SCOPE_CMDLINE, "VPATH"))
1265 		return;
1266 
1267 	vpath = Var_Subst("${VPATH}", SCOPE_CMDLINE, VARE_EVAL);
1268 	/* TODO: handle errors */
1269 	path = vpath;
1270 	do {
1271 		char *p;
1272 		/* skip to end of directory */
1273 		for (p = path; *p != ':' && *p != '\0'; p++)
1274 			continue;
1275 		/* Save terminator character so know when to stop */
1276 		savec = *p;
1277 		*p = '\0';
1278 		/* Add directory to search path */
1279 		(void)SearchPath_Add(&dirSearchPath, path);
1280 		*p = savec;
1281 		path = p + 1;
1282 	} while (savec == ':');
1283 	free(vpath);
1284 }
1285 
1286 static void
1287 ReadAllMakefiles(const StringList *makefiles)
1288 {
1289 	StringListNode *ln;
1290 
1291 	for (ln = makefiles->first; ln != NULL; ln = ln->next) {
1292 		const char *fname = ln->datum;
1293 		if (!ReadMakefile(fname))
1294 			Fatal("%s: cannot open %s.", progname, fname);
1295 	}
1296 }
1297 
1298 static void
1299 ReadFirstDefaultMakefile(void)
1300 {
1301 	StringList makefiles = LST_INIT;
1302 	StringListNode *ln;
1303 	char *prefs = Var_Subst("${.MAKE.MAKEFILE_PREFERENCE}",
1304 	    SCOPE_CMDLINE, VARE_EVAL);
1305 	/* TODO: handle errors */
1306 
1307 	AppendWords(&makefiles, prefs);
1308 
1309 	for (ln = makefiles.first; ln != NULL; ln = ln->next)
1310 		if (ReadMakefile(ln->datum))
1311 			break;
1312 
1313 	Lst_Done(&makefiles);
1314 	free(prefs);
1315 }
1316 
1317 /*
1318  * Initialize variables such as MAKE, MACHINE, .MAKEFLAGS.
1319  * Initialize a few modules.
1320  * Parse the arguments from MAKEFLAGS and the command line.
1321  */
1322 static void
1323 main_Init(int argc, char **argv)
1324 {
1325 	struct stat sa;
1326 	const char *machine;
1327 	const char *machine_arch;
1328 	char *syspath = getenv("MAKESYSPATH");
1329 	struct utsname utsname;
1330 
1331 	/* default to writing debug to stderr */
1332 	opts.debug_file = stderr;
1333 
1334 	Str_Intern_Init();
1335 	HashTable_Init(&cached_realpaths);
1336 
1337 #ifdef SIGINFO
1338 	(void)bmake_signal(SIGINFO, siginfo);
1339 #endif
1340 
1341 	InitRandom();
1342 
1343 	progname = str_basename(argv[0]);
1344 
1345 	UnlimitFiles();
1346 
1347 	if (uname(&utsname) == -1) {
1348 		(void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
1349 		    strerror(errno));
1350 		exit(2);
1351 	}
1352 
1353 	machine = InitVarMachine(&utsname);
1354 	machine_arch = InitVarMachineArch();
1355 
1356 	myPid = getpid();	/* remember this for vFork() */
1357 
1358 	/* Just in case MAKEOBJDIR wants us to do something tricky. */
1359 	Targ_Init();
1360 #ifdef FORCE_MAKE_OS
1361 	Global_Set_ReadOnly(".MAKE.OS", FORCE_MAKE_OS);
1362 #else
1363 	Global_Set_ReadOnly(".MAKE.OS", utsname.sysname);
1364 #endif
1365 	Global_Set("MACHINE", machine);
1366 	Global_Set("MACHINE_ARCH", machine_arch);
1367 #ifdef MAKE_VERSION
1368 	Global_Set("MAKE_VERSION", MAKE_VERSION);
1369 #endif
1370 	Global_Set_ReadOnly(".newline", "\n");
1371 #ifndef MAKEFILE_PREFERENCE_LIST
1372 	/* This is the traditional preference for makefiles. */
1373 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
1374 #endif
1375 	Global_Set(".MAKE.MAKEFILE_PREFERENCE", MAKEFILE_PREFERENCE_LIST);
1376 	Global_Set(".MAKE.DEPENDFILE", ".depend");
1377 	/* Tell makefiles like jobs.mk whether we support -jC */
1378 #ifdef _SC_NPROCESSORS_ONLN
1379 	Global_Set_ReadOnly(".MAKE.JOBS.C", "yes");
1380 #else
1381 	Global_Set_ReadOnly(".MAKE.JOBS.C", "no");
1382 #endif
1383 
1384 	CmdOpts_Init();
1385 	allPrecious = false;	/* Remove targets when interrupted */
1386 	deleteOnError = false;	/* Historical default behavior */
1387 	jobsRunning = false;
1388 
1389 	maxJobTokens = opts.maxJobs;
1390 	ignorePWD = false;
1391 
1392 	/*
1393 	 * Initialize the parsing, directory and variable modules to prepare
1394 	 * for the reading of inclusion paths and variable settings on the
1395 	 * command line
1396 	 */
1397 
1398 	/*
1399 	 * Initialize various variables.
1400 	 *	MAKE also gets this name, for compatibility
1401 	 *	.MAKEFLAGS gets set to the empty string just in case.
1402 	 *	MFLAGS also gets initialized empty, for compatibility.
1403 	 */
1404 	Parse_Init();
1405 	InitVarMake(argv[0]);
1406 	Global_Set(MAKEFLAGS, "");
1407 	Global_Set(".MAKEOVERRIDES", "");
1408 	Global_Set("MFLAGS", "");
1409 	Global_Set(".ALLTARGETS", "");
1410 	Global_Set_ReadOnly(".MAKE.LEVEL.ENV", MAKE_LEVEL_ENV);
1411 
1412 	/* Set some other useful variables. */
1413 	{
1414 		char buf[64];
1415 		const char *ep = getenv(MAKE_LEVEL_ENV);
1416 
1417 		makelevel = ep != NULL && ep[0] != '\0' ? atoi(ep) : 0;
1418 		if (makelevel < 0)
1419 			makelevel = 0;
1420 		snprintf(buf, sizeof buf, "%d", makelevel);
1421 		Global_Set(".MAKE.LEVEL", buf);
1422 		snprintf(buf, sizeof buf, "%u", myPid);
1423 		Global_Set_ReadOnly(".MAKE.PID", buf);
1424 		snprintf(buf, sizeof buf, "%u", getppid());
1425 		Global_Set_ReadOnly(".MAKE.PPID", buf);
1426 		snprintf(buf, sizeof buf, "%u", getuid());
1427 		Global_Set_ReadOnly(".MAKE.UID", buf);
1428 		snprintf(buf, sizeof buf, "%u", getgid());
1429 		Global_Set_ReadOnly(".MAKE.GID", buf);
1430 	}
1431 	if (makelevel > 0) {
1432 		char pn[1024];
1433 		snprintf(pn, sizeof pn, "%s[%d]", progname, makelevel);
1434 		progname = bmake_strdup(pn);
1435 	}
1436 
1437 #ifdef USE_META
1438 	meta_init();
1439 #endif
1440 	Dir_Init();
1441 
1442 	{
1443 		char *makeflags = explode(getenv("MAKEFLAGS"));
1444 		Main_ParseArgLine(makeflags);
1445 		free(makeflags);
1446 	}
1447 
1448 	if (getcwd(curdir, MAXPATHLEN) == NULL) {
1449 		(void)fprintf(stderr, "%s: getcwd: %s.\n",
1450 		    progname, strerror(errno));
1451 		exit(2);
1452 	}
1453 
1454 	MainParseArgs(argc, argv);
1455 
1456 	if (opts.enterFlag)
1457 		printf("%s: Entering directory `%s'\n", progname, curdir);
1458 
1459 	if (stat(curdir, &sa) == -1) {
1460 		(void)fprintf(stderr, "%s: %s: %s.\n",
1461 		    progname, curdir, strerror(errno));
1462 		exit(2);
1463 	}
1464 
1465 #ifndef NO_PWD_OVERRIDE
1466 	HandlePWD(&sa);
1467 #endif
1468 	Global_Set(".CURDIR", curdir);
1469 
1470 	InitObjdir(machine, machine_arch);
1471 
1472 	Arch_Init();
1473 	Suff_Init();
1474 	Trace_Init(tracefile);
1475 
1476 	defaultNode = NULL;
1477 	(void)time(&now);
1478 
1479 	Trace_Log(MAKESTART, NULL);
1480 
1481 	InitVarTargets();
1482 
1483 	InitDefSysIncPath(syspath);
1484 }
1485 
1486 /*
1487  * Read the system makefile followed by either makefile, Makefile or the
1488  * files given by the -f option. Exit on parse errors.
1489  */
1490 static void
1491 main_ReadFiles(void)
1492 {
1493 
1494 	if (Lst_IsEmpty(&sysIncPath->dirs))
1495 		SearchPath_AddAll(sysIncPath, defSysIncPath);
1496 
1497 	Dir_SetSYSPATH();
1498 	if (!opts.noBuiltins)
1499 		ReadBuiltinRules();
1500 
1501 	posix_state = PS_MAYBE_NEXT_LINE;
1502 	if (!Lst_IsEmpty(&opts.makefiles))
1503 		ReadAllMakefiles(&opts.makefiles);
1504 	else
1505 		ReadFirstDefaultMakefile();
1506 }
1507 
1508 /* Compute the dependency graph. */
1509 static void
1510 main_PrepareMaking(void)
1511 {
1512 	/* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1513 	if (!opts.noBuiltins || opts.printVars == PVM_NONE) {
1514 		makeDependfile = Var_Subst("${.MAKE.DEPENDFILE}",
1515 		    SCOPE_CMDLINE, VARE_EVAL);
1516 		if (makeDependfile[0] != '\0') {
1517 			/* TODO: handle errors */
1518 			doing_depend = true;
1519 			(void)ReadMakefile(makeDependfile);
1520 			doing_depend = false;
1521 		}
1522 	}
1523 
1524 	if (enterFlagObj)
1525 		printf("%s: Entering directory `%s'\n", progname, objdir);
1526 
1527 	MakeMode();
1528 
1529 	{
1530 		FStr makeflags = Var_Value(SCOPE_GLOBAL, MAKEFLAGS);
1531 		Global_Append("MFLAGS", makeflags.str);
1532 		FStr_Done(&makeflags);
1533 	}
1534 
1535 	InitMaxJobs();
1536 
1537 	if (!opts.compatMake && !forceJobs)
1538 		opts.compatMake = true;
1539 
1540 	if (!opts.compatMake)
1541 		Job_ServerStart(maxJobTokens, jp_0, jp_1);
1542 	DEBUG5(JOB, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1543 	    jp_0, jp_1, opts.maxJobs, maxJobTokens, opts.compatMake ? 1 : 0);
1544 
1545 	if (opts.printVars == PVM_NONE)
1546 		Main_ExportMAKEFLAGS(true);	/* initial export */
1547 
1548 	InitVpath();
1549 
1550 	/*
1551 	 * Now that all search paths have been read for suffixes et al, it's
1552 	 * time to add the default search path to their lists...
1553 	 */
1554 	Suff_ExtendPaths();
1555 
1556 	/*
1557 	 * Propagate attributes through :: dependency lists.
1558 	 */
1559 	Targ_Propagate();
1560 
1561 	/* print the initial graph, if the user requested it */
1562 	if (DEBUG(GRAPH1))
1563 		Targ_PrintGraph(1);
1564 }
1565 
1566 /*
1567  * Make the targets.
1568  * If the -v or -V options are given, print variables instead.
1569  * Return whether any of the targets is out-of-date.
1570  */
1571 static bool
1572 main_Run(void)
1573 {
1574 	if (opts.printVars != PVM_NONE) {
1575 		/* print the values of any variables requested by the user */
1576 		doPrintVars();
1577 		return false;
1578 	} else {
1579 		return runTargets();
1580 	}
1581 }
1582 
1583 /* Clean up after making the targets. */
1584 static void
1585 main_CleanUp(void)
1586 {
1587 #ifdef CLEANUP
1588 	Lst_DoneFree(&opts.variables);
1589 	Lst_DoneFree(&opts.makefiles);
1590 	Lst_DoneFree(&opts.create);
1591 #endif
1592 
1593 	if (DEBUG(GRAPH2))
1594 		Targ_PrintGraph(2);
1595 
1596 	Trace_Log(MAKEEND, NULL);
1597 
1598 	if (enterFlagObj)
1599 		printf("%s: Leaving directory `%s'\n", progname, objdir);
1600 	if (opts.enterFlag)
1601 		printf("%s: Leaving directory `%s'\n", progname, curdir);
1602 
1603 	Var_Stats();
1604 	Targ_Stats();
1605 
1606 #ifdef USE_META
1607 	meta_finish();
1608 #endif
1609 #ifdef CLEANUP
1610 	Suff_End();
1611 	Targ_End();
1612 	Arch_End();
1613 	Parse_End();
1614 	Dir_End();
1615 	Job_End();
1616 #endif
1617 	Trace_End();
1618 #ifdef CLEANUP
1619 	Str_Intern_End();
1620 #endif
1621 }
1622 
1623 /* Determine the exit code. */
1624 static int
1625 main_Exit(bool outOfDate)
1626 {
1627 	if ((opts.strict && main_errors > 0) || parseErrors > 0)
1628 		return 2;	/* Not 1 so -q can distinguish error */
1629 	return outOfDate ? 1 : 0;
1630 }
1631 
1632 int
1633 main(int argc, char **argv)
1634 {
1635 	bool outOfDate;
1636 
1637 	main_Init(argc, argv);
1638 	main_ReadFiles();
1639 	main_PrepareMaking();
1640 	outOfDate = main_Run();
1641 	main_CleanUp();
1642 	return main_Exit(outOfDate);
1643 }
1644 
1645 /*
1646  * Open and parse the given makefile, with all its side effects.
1647  * Return false if the file could not be opened.
1648  */
1649 static bool
1650 ReadMakefile(const char *fname)
1651 {
1652 	int fd;
1653 	char *name, *path = NULL;
1654 
1655 	if (strcmp(fname, "-") == 0) {
1656 		Parse_File("(stdin)", -1);
1657 		Var_Set(SCOPE_INTERNAL, "MAKEFILE", "");
1658 	} else {
1659 		if (strncmp(fname, ".../", 4) == 0) {
1660 			name = Dir_FindHereOrAbove(curdir, fname + 4);
1661 			if (name != NULL) {
1662 				/* Dir_FindHereOrAbove returns dirname */
1663 				path = str_concat3(name, "/",
1664 				    str_basename(fname));
1665 				free(name);
1666 				fd = open(path, O_RDONLY);
1667 				if (fd != -1) {
1668 					fname = path;
1669 					goto found;
1670 				}
1671 			}
1672 		}
1673 		/* if we've chdir'd, rebuild the path name */
1674 		if (strcmp(curdir, objdir) != 0 && *fname != '/') {
1675 			path = str_concat3(curdir, "/", fname);
1676 			fd = open(path, O_RDONLY);
1677 			if (fd != -1) {
1678 				fname = path;
1679 				goto found;
1680 			}
1681 			free(path);
1682 
1683 			/* If curdir failed, try objdir (ala .depend) */
1684 			path = str_concat3(objdir, "/", fname);
1685 			fd = open(path, O_RDONLY);
1686 			if (fd != -1) {
1687 				fname = path;
1688 				goto found;
1689 			}
1690 		} else {
1691 			fd = open(fname, O_RDONLY);
1692 			if (fd != -1)
1693 				goto found;
1694 		}
1695 		/* look in -I and system include directories. */
1696 		name = Dir_FindFile(fname, parseIncPath);
1697 		if (name == NULL) {
1698 			SearchPath *sysInc = Lst_IsEmpty(&sysIncPath->dirs)
1699 			    ? defSysIncPath : sysIncPath;
1700 			name = Dir_FindFile(fname, sysInc);
1701 		}
1702 		if (name == NULL || (fd = open(name, O_RDONLY)) == -1) {
1703 			free(name);
1704 			free(path);
1705 			return false;
1706 		}
1707 		fname = name;
1708 		/*
1709 		 * set the MAKEFILE variable desired by System V fans -- the
1710 		 * placement of the setting here means it gets set to the last
1711 		 * makefile specified, as it is set by SysV make.
1712 		 */
1713 found:
1714 		if (!doing_depend)
1715 			Var_Set(SCOPE_INTERNAL, "MAKEFILE", fname);
1716 		Parse_File(fname, fd);
1717 	}
1718 	free(path);
1719 	return true;
1720 }
1721 
1722 /* populate av for Cmd_Exec and Compat_RunCommand */
1723 int
1724 Cmd_Argv(const char *cmd, size_t cmd_len, const char **av, size_t avsz,
1725     char *cmd_file, size_t cmd_filesz, bool eflag, bool xflag)
1726 {
1727 	int ac = 0;
1728 	int cmd_fd = -1;
1729 
1730 	if (shellPath == NULL)
1731 		Shell_Init();
1732 
1733 	if (cmd_file != NULL) {
1734 		if (cmd_len == 0)
1735 			cmd_len = strlen(cmd);
1736 
1737 		if (cmd_len > MAKE_CMDLEN_LIMIT) {
1738 			cmd_fd = mkTempFile(NULL, cmd_file, cmd_filesz);
1739 			if (cmd_fd >= 0) {
1740 				ssize_t n;
1741 
1742 				n = write(cmd_fd, cmd, cmd_len);
1743 				close(cmd_fd);
1744 				if (n < (ssize_t)cmd_len) {
1745 					unlink(cmd_file);
1746 					cmd_fd = -1;
1747 				}
1748 			}
1749 		} else
1750 			cmd_file[0] = '\0';
1751 	}
1752 
1753 	if (avsz < 4 || (eflag && avsz < 5))
1754 		return -1;
1755 
1756 	/* The following works for any of the builtin shell specs. */
1757 	av[ac++] = shellPath;
1758 	if (eflag)
1759 		av[ac++] = shellErrFlag;
1760 	if (cmd_fd >= 0) {
1761 		if (xflag)
1762 			av[ac++] = "-x";
1763 		av[ac++] = cmd_file;
1764 	} else {
1765 		av[ac++] = xflag ? "-xc" : "-c";
1766 		av[ac++] = cmd;
1767 	}
1768 	av[ac] = NULL;
1769 	return ac;
1770 }
1771 
1772 /*
1773  * Execute the command in cmd, and return its output (only stdout, not
1774  * stderr, possibly empty).  In the output, replace newlines with spaces.
1775  */
1776 char *
1777 Cmd_Exec(const char *cmd, char **error)
1778 {
1779 	const char *args[4];	/* Arguments for invoking the shell */
1780 	int pipefds[2];
1781 	int cpid;		/* Child PID */
1782 	int pid;		/* PID from wait() */
1783 	WAIT_T status;		/* command exit status */
1784 	Buffer buf;		/* buffer to store the result */
1785 	ssize_t bytes_read;
1786 	char *output;
1787 	char *p;
1788 	int saved_errno;
1789 	char cmd_file[MAXPATHLEN];
1790 
1791 	DEBUG1(VAR, "Capturing the output of command \"%s\"\n", cmd);
1792 
1793 	if (Cmd_Argv(cmd, 0, args, 4, cmd_file, sizeof(cmd_file), false, false) < 0
1794 	    || pipe(pipefds) == -1) {
1795 		*error = str_concat3(
1796 		    "Couldn't create pipe for \"", cmd, "\"");
1797 		return bmake_strdup("");
1798 	}
1799 
1800 	Var_ReexportVars(SCOPE_GLOBAL);
1801 
1802 	switch (cpid = FORK_FUNCTION()) {
1803 	case 0:
1804 		(void)close(pipefds[0]);
1805 		(void)dup2(pipefds[1], STDOUT_FILENO);
1806 		(void)close(pipefds[1]);
1807 
1808 		(void)execv(shellPath, UNCONST(args));
1809 		_exit(1);
1810 		/* NOTREACHED */
1811 
1812 	case -1:
1813 		*error = str_concat3("Couldn't exec \"", cmd, "\"");
1814 		return bmake_strdup("");
1815 	}
1816 
1817 	(void)close(pipefds[1]);	/* No need for the writing half */
1818 
1819 	saved_errno = 0;
1820 	Buf_Init(&buf);
1821 
1822 	do {
1823 		char result[BUFSIZ];
1824 		bytes_read = read(pipefds[0], result, sizeof result);
1825 		if (bytes_read > 0)
1826 			Buf_AddBytes(&buf, result, (size_t)bytes_read);
1827 	} while (bytes_read > 0 || (bytes_read == -1 && errno == EINTR));
1828 	if (bytes_read == -1)
1829 		saved_errno = errno;
1830 
1831 	(void)close(pipefds[0]); /* Close the input side of the pipe. */
1832 
1833 	while ((pid = waitpid(cpid, &status, 0)) != cpid && pid >= 0)
1834 		JobReapChild(pid, status, false);
1835 
1836 	if (Buf_EndsWith(&buf, '\n'))
1837 		buf.data[buf.len - 1] = '\0';
1838 
1839 	output = Buf_DoneData(&buf);
1840 	for (p = output; *p != '\0'; p++)
1841 		if (*p == '\n')
1842 			*p = ' ';
1843 
1844 	if (WIFSIGNALED(status))
1845 		*error = str_concat3("\"", cmd, "\" exited on a signal");
1846 	else if (WEXITSTATUS(status) != 0) {
1847 		Buffer errBuf;
1848 		Buf_Init(&errBuf);
1849 		Buf_AddStr(&errBuf, "Command \"");
1850 		Buf_AddStr(&errBuf, cmd);
1851 		Buf_AddStr(&errBuf, "\" exited with status ");
1852 		Buf_AddInt(&errBuf, WEXITSTATUS(status));
1853 		*error = Buf_DoneData(&errBuf);
1854 	} else if (saved_errno != 0)
1855 		*error = str_concat3(
1856 		    "Couldn't read shell's output for \"", cmd, "\"");
1857 	else
1858 		*error = NULL;
1859 	if (cmd_file[0] != '\0')
1860 		unlink(cmd_file);
1861 	return output;
1862 }
1863 
1864 /*
1865  * Print a printf-style error message.
1866  *
1867  * In default mode, this error message has no consequences, for compatibility
1868  * reasons, in particular it does not affect the exit status.  Only in lint
1869  * mode (-dL) it does.
1870  */
1871 void
1872 Error(const char *fmt, ...)
1873 {
1874 	va_list ap;
1875 	FILE *f;
1876 
1877 	f = opts.debug_file;
1878 	if (f == stdout)
1879 		f = stderr;
1880 	(void)fflush(stdout);
1881 
1882 	for (;;) {
1883 		fprintf(f, "%s: ", progname);
1884 		va_start(ap, fmt);
1885 		(void)vfprintf(f, fmt, ap);
1886 		va_end(ap);
1887 		(void)fprintf(f, "\n");
1888 		(void)fflush(f);
1889 		if (f == stderr)
1890 			break;
1891 		f = stderr;
1892 	}
1893 	main_errors++;
1894 }
1895 
1896 /*
1897  * Wait for any running jobs to finish, then produce an error message,
1898  * finally exit immediately.
1899  *
1900  * Exiting immediately differs from Parse_Error, which exits only after the
1901  * current top-level makefile has been parsed completely.
1902  */
1903 void
1904 Fatal(const char *fmt, ...)
1905 {
1906 	va_list ap;
1907 
1908 	if (jobsRunning)
1909 		Job_Wait();
1910 
1911 	(void)fflush(stdout);
1912 	fprintf(stderr, "%s: ", progname);
1913 	va_start(ap, fmt);
1914 	(void)vfprintf(stderr, fmt, ap);
1915 	va_end(ap);
1916 	(void)fprintf(stderr, "\n");
1917 	(void)fflush(stderr);
1918 	PrintStackTrace(true);
1919 
1920 	PrintOnError(NULL, "\n");
1921 
1922 	if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1923 		Targ_PrintGraph(2);
1924 	Trace_Log(MAKEERROR, NULL);
1925 	exit(2);		/* Not 1 so -q can distinguish error */
1926 }
1927 
1928 /*
1929  * Major exception once jobs are being created.
1930  * Kills all jobs, prints a message and exits.
1931  */
1932 void
1933 Punt(const char *fmt, ...)
1934 {
1935 	va_list ap;
1936 
1937 	(void)fflush(stdout);
1938 	(void)fprintf(stderr, "%s: ", progname);
1939 	va_start(ap, fmt);
1940 	(void)vfprintf(stderr, fmt, ap);
1941 	va_end(ap);
1942 	(void)fprintf(stderr, "\n");
1943 	(void)fflush(stderr);
1944 
1945 	PrintOnError(NULL, "\n");
1946 
1947 	DieHorribly();
1948 }
1949 
1950 /* Exit without giving a message. */
1951 void
1952 DieHorribly(void)
1953 {
1954 	if (jobsRunning)
1955 		Job_AbortAll();
1956 	if (DEBUG(GRAPH2))
1957 		Targ_PrintGraph(2);
1958 	Trace_Log(MAKEERROR, NULL);
1959 	exit(2);		/* Not 1 so -q can distinguish error */
1960 }
1961 
1962 int
1963 unlink_file(const char *file)
1964 {
1965 	struct stat st;
1966 
1967 	if (lstat(file, &st) == -1)
1968 		return -1;
1969 
1970 	if (S_ISDIR(st.st_mode)) {
1971 		/*
1972 		 * POSIX says for unlink: "The path argument shall not name
1973 		 * a directory unless [...]".
1974 		 */
1975 		errno = EISDIR;
1976 		return -1;
1977 	}
1978 	return unlink(file);
1979 }
1980 
1981 static void
1982 write_all(int fd, const void *data, size_t n)
1983 {
1984 	const char *mem = data;
1985 
1986 	while (n > 0) {
1987 		ssize_t written = write(fd, mem, n);
1988 		/* XXX: Should this EAGAIN be EINTR? */
1989 		if (written == -1 && errno == EAGAIN)
1990 			continue;
1991 		if (written == -1)
1992 			break;
1993 		mem += written;
1994 		n -= (size_t)written;
1995 	}
1996 }
1997 
1998 /* Print why exec failed, avoiding stdio. */
1999 void MAKE_ATTR_DEAD
2000 execDie(const char *func, const char *arg)
2001 {
2002 	char msg[1024];
2003 	int len;
2004 
2005 	len = snprintf(msg, sizeof(msg), "%s: %s(%s) failed (%s)\n",
2006 	    progname, func, arg, strerror(errno));
2007 	write_all(STDERR_FILENO, msg, (size_t)len);
2008 	_exit(1);
2009 }
2010 
2011 static void
2012 purge_relative_cached_realpaths(void)
2013 {
2014 	HashIter hi;
2015 	bool more;
2016 
2017 	HashIter_Init(&hi, &cached_realpaths);
2018 	more = HashIter_Next(&hi);
2019 	while (more) {
2020 		HashEntry *he = hi.entry;
2021 		more = HashIter_Next(&hi);
2022 		if (he->key[0] != '/') {
2023 			DEBUG1(DIR, "cached_realpath: purging %s\n", he->key);
2024 			free(he->value);
2025 			HashTable_DeleteEntry(&cached_realpaths, he);
2026 		}
2027 	}
2028 }
2029 
2030 const char *
2031 cached_realpath(const char *pathname, char *resolved)
2032 {
2033 	const char *rp;
2034 
2035 	if (pathname == NULL || pathname[0] == '\0')
2036 		return NULL;
2037 
2038 	rp = HashTable_FindValue(&cached_realpaths, pathname);
2039 	if (rp != NULL) {
2040 		snprintf(resolved, MAXPATHLEN, "%s", rp);
2041 		return resolved;
2042 	}
2043 
2044 	rp = realpath(pathname, resolved);
2045 	if (rp != NULL) {
2046 		HashTable_Set(&cached_realpaths, pathname, bmake_strdup(rp));
2047 		DEBUG2(DIR, "cached_realpath: %s -> %s\n", pathname, rp);
2048 		return resolved;
2049 	}
2050 
2051 	/* should we negative-cache? */
2052 	return NULL;
2053 }
2054 
2055 /*
2056  * Return true if we should die without noise.
2057  * For example our failing child was a sub-make or failure happened elsewhere.
2058  */
2059 bool
2060 shouldDieQuietly(GNode *gn, int bf)
2061 {
2062 	static int quietly = -1;
2063 
2064 	if (quietly < 0) {
2065 		if (DEBUG(JOB) ||
2066 		    !GetBooleanExpr("${.MAKE.DIE_QUIETLY}", true))
2067 			quietly = 0;
2068 		else if (bf >= 0)
2069 			quietly = bf;
2070 		else
2071 			quietly = (gn != NULL && (gn->type & OP_MAKE)) ? 1 : 0;
2072 	}
2073 	return quietly != 0;
2074 }
2075 
2076 static void
2077 SetErrorVars(GNode *gn)
2078 {
2079 	StringListNode *ln;
2080 	char sts[16];
2081 
2082 	/*
2083 	 * We can print this even if there is no .ERROR target.
2084 	 */
2085 	snprintf(sts, sizeof(sts), "%d", gn->exit_status);
2086 	Global_Set(".ERROR_EXIT", sts);
2087 	Global_Set(".ERROR_TARGET", gn->name);
2088 	Global_Delete(".ERROR_CMD");
2089 
2090 	for (ln = gn->commands.first; ln != NULL; ln = ln->next) {
2091 		const char *cmd = ln->datum;
2092 
2093 		if (cmd == NULL)
2094 			break;
2095 		Global_Append(".ERROR_CMD", cmd);
2096 	}
2097 }
2098 
2099 /*
2100  * Print some helpful information in case of an error.
2101  * The caller should exit soon after calling this function.
2102  */
2103 void
2104 PrintOnError(GNode *gn, const char *msg)
2105 {
2106 	static GNode *errorNode = NULL;
2107 	StringListNode *ln;
2108 
2109 	if (DEBUG(HASH)) {
2110 		Targ_Stats();
2111 		Var_Stats();
2112 	}
2113 
2114 	if (errorNode != NULL)
2115 		return;		/* we've been here! */
2116 
2117 	printf("%s%s: stopped", msg, progname);
2118 	ln = opts.create.first;
2119 	if (ln != NULL || mainNode != NULL) {
2120 		printf(" making \"");
2121 		if (ln != NULL) {
2122 			printf("%s", (const char *)ln->datum);
2123 			for (ln = ln->next; ln != NULL; ln = ln->next)
2124 				printf(" %s", (const char *)ln->datum);
2125 		} else
2126 			printf("%s", mainNode->name);
2127 		printf("\"");
2128 	}
2129 	printf(" in %s\n", curdir);
2130 
2131 	/* we generally want to keep quiet if a sub-make died */
2132 	if (shouldDieQuietly(gn, -1))
2133 		return;
2134 
2135 	if (gn != NULL)
2136 		SetErrorVars(gn);
2137 
2138 	{
2139 		char *errorVarsValues = Var_Subst(
2140 		    "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
2141 		    SCOPE_GLOBAL, VARE_EVAL);
2142 		/* TODO: handle errors */
2143 		printf("%s", errorVarsValues);
2144 		free(errorVarsValues);
2145 	}
2146 
2147 	fflush(stdout);
2148 
2149 	/*
2150 	 * Finally, see if there is a .ERROR target, and run it if so.
2151 	 */
2152 	errorNode = Targ_FindNode(".ERROR");
2153 	if (errorNode != NULL) {
2154 		errorNode->type |= OP_SPECIAL;
2155 		Compat_Make(errorNode, errorNode);
2156 	}
2157 }
2158 
2159 void
2160 Main_ExportMAKEFLAGS(bool first)
2161 {
2162 	static bool once = true;
2163 	char *flags;
2164 
2165 	if (once != first)
2166 		return;
2167 	once = false;
2168 
2169 	flags = Var_Subst(
2170 	    "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
2171 	    SCOPE_CMDLINE, VARE_EVAL);
2172 	/* TODO: handle errors */
2173 	if (flags[0] != '\0')
2174 		setenv("MAKEFLAGS", flags, 1);
2175 	free(flags);
2176 }
2177 
2178 char *
2179 getTmpdir(void)
2180 {
2181 	static char *tmpdir = NULL;
2182 	struct stat st;
2183 
2184 	if (tmpdir != NULL)
2185 		return tmpdir;
2186 
2187 	/* Honor $TMPDIR if it is valid, strip a trailing '/'. */
2188 	tmpdir = Var_Subst("${TMPDIR:tA:U" _PATH_TMP ":S,/$,,W}/",
2189 	    SCOPE_GLOBAL, VARE_EVAL);
2190 	/* TODO: handle errors */
2191 
2192 	if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
2193 		free(tmpdir);
2194 		tmpdir = bmake_strdup(_PATH_TMP);
2195 	}
2196 	return tmpdir;
2197 }
2198 
2199 /*
2200  * Create and open a temp file using "pattern".
2201  * If tfile is provided, set it to a copy of the filename created.
2202  * Otherwise unlink the file once open.
2203  */
2204 int
2205 mkTempFile(const char *pattern, char *tfile, size_t tfile_sz)
2206 {
2207 	static char *tmpdir = NULL;
2208 	char tbuf[MAXPATHLEN];
2209 	int fd;
2210 
2211 	if (pattern == NULL)
2212 		pattern = TMPPAT;
2213 	if (tmpdir == NULL)
2214 		tmpdir = getTmpdir();
2215 	if (tfile == NULL) {
2216 		tfile = tbuf;
2217 		tfile_sz = sizeof tbuf;
2218 	}
2219 
2220 	if (pattern[0] == '/')
2221 		snprintf(tfile, tfile_sz, "%s", pattern);
2222 	else
2223 		snprintf(tfile, tfile_sz, "%s%s", tmpdir, pattern);
2224 
2225 	if ((fd = mkstemp(tfile)) < 0)
2226 		Punt("Could not create temporary file %s: %s", tfile,
2227 		    strerror(errno));
2228 	if (tfile == tbuf)
2229 		unlink(tfile);	/* we just want the descriptor */
2230 
2231 	return fd;
2232 }
2233 
2234 /*
2235  * Convert a string representation of a boolean into a boolean value.
2236  * Anything that looks like "No", "False", "Off", "0" etc. is false,
2237  * the empty string is the fallback, everything else is true.
2238  */
2239 bool
2240 ParseBoolean(const char *s, bool fallback)
2241 {
2242 	char ch = ch_tolower(s[0]);
2243 	if (ch == '\0')
2244 		return fallback;
2245 	if (ch == '0' || ch == 'f' || ch == 'n')
2246 		return false;
2247 	if (ch == 'o')
2248 		return ch_tolower(s[1]) != 'f';
2249 	return true;
2250 }
2251