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