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