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