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