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