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