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