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