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