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