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