Home | History | Annotate | Line # | Download | only in make
main.c revision 1.524
      1 /*	$NetBSD: main.c,v 1.524 2021/02/01 19:53:31 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.524 2021/02/01 19:53:31 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 		Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
    413 		Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    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 	Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
    431 	Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    432 	Var_Set(".MAKE.JOBS", argvalue, VAR_GLOBAL);
    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 	Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
    450 	Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    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 		Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
    462 		Var_Set(MAKE_MODE, "compat", VAR_GLOBAL);
    463 		break;
    464 	case 'C':
    465 		MainParseArgChdir(argvalue);
    466 		break;
    467 	case 'D':
    468 		if (argvalue[0] == '\0') return FALSE;
    469 		Var_Set(argvalue, "1", VAR_GLOBAL);
    470 		Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
    471 		Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    472 		break;
    473 	case 'I':
    474 		Parse_AddIncludeDir(argvalue);
    475 		Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
    476 		Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    477 		break;
    478 	case 'J':
    479 		MainParseArgJobsInternal(argvalue);
    480 		break;
    481 	case 'N':
    482 		opts.noExecute = TRUE;
    483 		opts.noRecursiveExecute = TRUE;
    484 		Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
    485 		break;
    486 	case 'S':
    487 		opts.keepgoing = FALSE;
    488 		Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
    489 		break;
    490 	case 'T':
    491 		tracefile = bmake_strdup(argvalue);
    492 		Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
    493 		Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    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 		Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
    501 		Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    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 		Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
    510 		break;
    511 	case 'd':
    512 		/* If '-d-opts' don't pass to children */
    513 		if (argvalue[0] == '-')
    514 			argvalue++;
    515 		else {
    516 			Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
    517 			Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    518 		}
    519 		MainParseArgDebug(argvalue);
    520 		break;
    521 	case 'e':
    522 		opts.checkEnvFirst = TRUE;
    523 		Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
    524 		break;
    525 	case 'f':
    526 		Lst_Append(&opts.makefiles, bmake_strdup(argvalue));
    527 		break;
    528 	case 'i':
    529 		opts.ignoreErrors = TRUE;
    530 		Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
    531 		break;
    532 	case 'j':
    533 		MainParseArgJobs(argvalue);
    534 		break;
    535 	case 'k':
    536 		opts.keepgoing = TRUE;
    537 		Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
    538 		break;
    539 	case 'm':
    540 		MainParseArgSysInc(argvalue);
    541 		/* XXX: why no Var_Append? */
    542 		break;
    543 	case 'n':
    544 		opts.noExecute = TRUE;
    545 		Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
    546 		break;
    547 	case 'q':
    548 		opts.queryFlag = TRUE;
    549 		/* Kind of nonsensical, wot? */
    550 		Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
    551 		break;
    552 	case 'r':
    553 		opts.noBuiltins = TRUE;
    554 		Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
    555 		break;
    556 	case 's':
    557 		opts.beSilent = TRUE;
    558 		Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
    559 		break;
    560 	case 't':
    561 		opts.touchFlag = TRUE;
    562 		Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
    563 		break;
    564 	case 'w':
    565 		opts.enterFlag = TRUE;
    566 		Var_Append(MAKEFLAGS, "-w", VAR_GLOBAL);
    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, VAR_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", VAR_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 			Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
    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, VAR_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, VAR_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}", VAR_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, VAR_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, VAR_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, VAR_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, VAR_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 nodes. */
    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 		Var_Set(".TARGETS", "", VAR_GLOBAL);
    961 		return;
    962 	}
    963 
    964 	for (ln = opts.create.first; ln != NULL; ln = ln->next) {
    965 		char *name = ln->datum;
    966 		Var_Append(".TARGETS", name, VAR_GLOBAL);
    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)
    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  * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
   1033  * since the value of curdir can vary depending on how we got
   1034  * here.  Ie sitting at a shell prompt (shell that provides $PWD)
   1035  * or via subdir.mk in which case its likely a shell which does
   1036  * not provide it.
   1037  *
   1038  * So, to stop it breaking this case only, we ignore PWD if
   1039  * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a variable expression.
   1040  */
   1041 static void
   1042 HandlePWD(const struct stat *curdir_st)
   1043 {
   1044 	char *pwd;
   1045 	FStr prefix, makeobjdir;
   1046 	struct stat pwd_st;
   1047 
   1048 	if (ignorePWD || (pwd = getenv("PWD")) == NULL)
   1049 		return;
   1050 
   1051 	prefix = Var_Value("MAKEOBJDIRPREFIX", VAR_CMDLINE);
   1052 	if (prefix.str != NULL) {
   1053 		FStr_Done(&prefix);
   1054 		return;
   1055 	}
   1056 
   1057 	makeobjdir = Var_Value("MAKEOBJDIR", VAR_CMDLINE);
   1058 	if (makeobjdir.str != NULL && strchr(makeobjdir.str, '$') != NULL)
   1059 		goto ignore_pwd;
   1060 
   1061 	if (stat(pwd, &pwd_st) == 0 &&
   1062 	    curdir_st->st_ino == pwd_st.st_ino &&
   1063 	    curdir_st->st_dev == pwd_st.st_dev)
   1064 		(void)strncpy(curdir, pwd, MAXPATHLEN);
   1065 
   1066 ignore_pwd:
   1067 	FStr_Done(&makeobjdir);
   1068 }
   1069 #endif
   1070 
   1071 /*
   1072  * Find the .OBJDIR.  If MAKEOBJDIRPREFIX, or failing that,
   1073  * MAKEOBJDIR is set in the environment, try only that value
   1074  * and fall back to .CURDIR if it does not exist.
   1075  *
   1076  * Otherwise, try _PATH_OBJDIR.MACHINE-MACHINE_ARCH, _PATH_OBJDIR.MACHINE,
   1077  * and * finally _PATH_OBJDIRPREFIX`pwd`, in that order.  If none
   1078  * of these paths exist, just use .CURDIR.
   1079  */
   1080 static void
   1081 InitObjdir(const char *machine, const char *machine_arch)
   1082 {
   1083 	Boolean writable;
   1084 
   1085 	Dir_InitCur(curdir);
   1086 	writable = GetBooleanVar("MAKE_OBJDIR_CHECK_WRITABLE", TRUE);
   1087 	(void)Main_SetObjdir(FALSE, "%s", curdir);
   1088 
   1089 	if (!SetVarObjdir(writable, "MAKEOBJDIRPREFIX", curdir) &&
   1090 	    !SetVarObjdir(writable, "MAKEOBJDIR", "") &&
   1091 	    !Main_SetObjdir(writable, "%s.%s-%s", _PATH_OBJDIR, machine, machine_arch) &&
   1092 	    !Main_SetObjdir(writable, "%s.%s", _PATH_OBJDIR, machine) &&
   1093 	    !Main_SetObjdir(writable, "%s", _PATH_OBJDIR))
   1094 		(void)Main_SetObjdir(writable, "%s%s", _PATH_OBJDIRPREFIX, curdir);
   1095 }
   1096 
   1097 /* get rid of resource limit on file descriptors */
   1098 static void
   1099 UnlimitFiles(void)
   1100 {
   1101 #if defined(MAKE_NATIVE) || (defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE))
   1102 	struct rlimit rl;
   1103 	if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
   1104 	    rl.rlim_cur != rl.rlim_max) {
   1105 		rl.rlim_cur = rl.rlim_max;
   1106 		(void)setrlimit(RLIMIT_NOFILE, &rl);
   1107 	}
   1108 #endif
   1109 }
   1110 
   1111 static void
   1112 CmdOpts_Init(void)
   1113 {
   1114 	opts.compatMake = FALSE;
   1115 	opts.debug = DEBUG_NONE;
   1116 	/* opts.debug_file has been initialized earlier */
   1117 	opts.strict = FALSE;
   1118 	opts.debugVflag = FALSE;
   1119 	opts.checkEnvFirst = FALSE;
   1120 	Lst_Init(&opts.makefiles);
   1121 	opts.ignoreErrors = FALSE;	/* Pay attention to non-zero returns */
   1122 	opts.maxJobs = 1;
   1123 	opts.keepgoing = FALSE;		/* Stop on error */
   1124 	opts.noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
   1125 	opts.noExecute = FALSE;		/* Execute all commands */
   1126 	opts.queryFlag = FALSE;
   1127 	opts.noBuiltins = FALSE;	/* Read the built-in rules */
   1128 	opts.beSilent = FALSE;		/* Print commands as executed */
   1129 	opts.touchFlag = FALSE;
   1130 	opts.printVars = PVM_NONE;
   1131 	Lst_Init(&opts.variables);
   1132 	opts.parseWarnFatal = FALSE;
   1133 	opts.enterFlag = FALSE;
   1134 	opts.varNoExportEnv = FALSE;
   1135 	Lst_Init(&opts.create);
   1136 }
   1137 
   1138 /*
   1139  * Initialize MAKE and .MAKE to the path of the executable, so that it can be
   1140  * found by execvp(3) and the shells, even after a chdir.
   1141  *
   1142  * If it's a relative path and contains a '/', resolve it to an absolute path.
   1143  * Otherwise keep it as is, assuming it will be found in the PATH.
   1144  */
   1145 static void
   1146 InitVarMake(const char *argv0)
   1147 {
   1148 	const char *make = argv0;
   1149 
   1150 	if (argv0[0] != '/' && strchr(argv0, '/') != NULL) {
   1151 		char pathbuf[MAXPATHLEN];
   1152 		const char *abspath = cached_realpath(argv0, pathbuf);
   1153 		struct stat st;
   1154 		if (abspath != NULL && abspath[0] == '/' &&
   1155 		    stat(make, &st) == 0)
   1156 			make = abspath;
   1157 	}
   1158 
   1159 	Var_Set("MAKE", make, VAR_GLOBAL);
   1160 	Var_Set(".MAKE", make, VAR_GLOBAL);
   1161 }
   1162 
   1163 /*
   1164  * Add the directories from the colon-separated syspath to defSysIncPath.
   1165  * After returning, the contents of syspath is unspecified.
   1166  */
   1167 static void
   1168 InitDefSysIncPath(char *syspath)
   1169 {
   1170 	static char defsyspath[] = _PATH_DEFSYSPATH;
   1171 	char *start, *cp;
   1172 
   1173 	/*
   1174 	 * If no user-supplied system path was given (through the -m option)
   1175 	 * add the directories from the DEFSYSPATH (more than one may be given
   1176 	 * as dir1:...:dirn) to the system include path.
   1177 	 */
   1178 	if (syspath == NULL || syspath[0] == '\0')
   1179 		syspath = defsyspath;
   1180 	else
   1181 		syspath = bmake_strdup(syspath);
   1182 
   1183 	for (start = syspath; *start != '\0'; start = cp) {
   1184 		for (cp = start; *cp != '\0' && *cp != ':'; cp++)
   1185 			continue;
   1186 		if (*cp == ':')
   1187 			*cp++ = '\0';
   1188 
   1189 		/* look for magic parent directory search string */
   1190 		if (strncmp(start, ".../", 4) == 0) {
   1191 			char *dir = Dir_FindHereOrAbove(curdir, start + 4);
   1192 			if (dir != NULL) {
   1193 				(void)SearchPath_Add(defSysIncPath, dir);
   1194 				free(dir);
   1195 			}
   1196 		} else {
   1197 			(void)SearchPath_Add(defSysIncPath, start);
   1198 		}
   1199 	}
   1200 
   1201 	if (syspath != defsyspath)
   1202 		free(syspath);
   1203 }
   1204 
   1205 static void
   1206 ReadBuiltinRules(void)
   1207 {
   1208 	StringListNode *ln;
   1209 	StringList sysMkPath = LST_INIT;
   1210 
   1211 	SearchPath_Expand(
   1212 	    Lst_IsEmpty(&sysIncPath->dirs) ? defSysIncPath : sysIncPath,
   1213 	    _PATH_DEFSYSMK,
   1214 	    &sysMkPath);
   1215 	if (Lst_IsEmpty(&sysMkPath))
   1216 		Fatal("%s: no system rules (%s).", progname, _PATH_DEFSYSMK);
   1217 
   1218 	for (ln = sysMkPath.first; ln != NULL; ln = ln->next)
   1219 		if (ReadMakefile(ln->datum) == 0)
   1220 			break;
   1221 
   1222 	if (ln == NULL)
   1223 		Fatal("%s: cannot open %s.",
   1224 		    progname, (const char *)sysMkPath.first->datum);
   1225 
   1226 	/* Free the list but not the actual filenames since these may still
   1227 	 * be used in GNodes. */
   1228 	Lst_Done(&sysMkPath);
   1229 }
   1230 
   1231 static void
   1232 InitMaxJobs(void)
   1233 {
   1234 	char *value;
   1235 	int n;
   1236 
   1237 	if (forceJobs || opts.compatMake ||
   1238 	    !Var_Exists(".MAKE.JOBS", VAR_GLOBAL))
   1239 		return;
   1240 
   1241 	(void)Var_Subst("${.MAKE.JOBS}", VAR_GLOBAL, VARE_WANTRES, &value);
   1242 	/* TODO: handle errors */
   1243 	n = (int)strtol(value, NULL, 0);
   1244 	if (n < 1) {
   1245 		(void)fprintf(stderr,
   1246 		    "%s: illegal value for .MAKE.JOBS "
   1247 		    "-- must be positive integer!\n",
   1248 		    progname);
   1249 		exit(2);	/* Not 1 so -q can distinguish error */
   1250 	}
   1251 
   1252 	if (n != opts.maxJobs) {
   1253 		Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
   1254 		Var_Append(MAKEFLAGS, value, VAR_GLOBAL);
   1255 	}
   1256 
   1257 	opts.maxJobs = n;
   1258 	maxJobTokens = opts.maxJobs;
   1259 	forceJobs = TRUE;
   1260 	free(value);
   1261 }
   1262 
   1263 /*
   1264  * For compatibility, look at the directories in the VPATH variable
   1265  * and add them to the search path, if the variable is defined. The
   1266  * variable's value is in the same format as the PATH environment
   1267  * variable, i.e. <directory>:<directory>:<directory>...
   1268  */
   1269 static void
   1270 InitVpath(void)
   1271 {
   1272 	char *vpath, savec, *path;
   1273 	if (!Var_Exists("VPATH", VAR_CMDLINE))
   1274 		return;
   1275 
   1276 	(void)Var_Subst("${VPATH}", VAR_CMDLINE, VARE_WANTRES, &vpath);
   1277 	/* TODO: handle errors */
   1278 	path = vpath;
   1279 	do {
   1280 		char *cp;
   1281 		/* skip to end of directory */
   1282 		for (cp = path; *cp != ':' && *cp != '\0'; cp++)
   1283 			continue;
   1284 		/* Save terminator character so know when to stop */
   1285 		savec = *cp;
   1286 		*cp = '\0';
   1287 		/* Add directory to search path */
   1288 		(void)SearchPath_Add(&dirSearchPath, path);
   1289 		*cp = savec;
   1290 		path = cp + 1;
   1291 	} while (savec == ':');
   1292 	free(vpath);
   1293 }
   1294 
   1295 static void
   1296 ReadAllMakefiles(StringList *makefiles)
   1297 {
   1298 	StringListNode *ln;
   1299 
   1300 	for (ln = makefiles->first; ln != NULL; ln = ln->next) {
   1301 		const char *fname = ln->datum;
   1302 		if (ReadMakefile(fname) != 0)
   1303 			Fatal("%s: cannot open %s.", progname, fname);
   1304 	}
   1305 }
   1306 
   1307 static void
   1308 ReadFirstDefaultMakefile(void)
   1309 {
   1310 	StringListNode *ln;
   1311 	char *prefs;
   1312 
   1313 	(void)Var_Subst("${" MAKE_MAKEFILE_PREFERENCE "}",
   1314 	    VAR_CMDLINE, VARE_WANTRES, &prefs);
   1315 	/* TODO: handle errors */
   1316 
   1317 	/* XXX: This should use a local list instead of opts.makefiles
   1318 	 * since these makefiles do not come from the command line.  They
   1319 	 * also have different semantics in that only the first file that
   1320 	 * is found is processed.  See ReadAllMakefiles. */
   1321 	(void)str2Lst_Append(&opts.makefiles, prefs);
   1322 
   1323 	for (ln = opts.makefiles.first; ln != NULL; ln = ln->next)
   1324 		if (ReadMakefile(ln->datum) == 0)
   1325 			break;
   1326 
   1327 	free(prefs);
   1328 }
   1329 
   1330 /*
   1331  * Initialize variables such as MAKE, MACHINE, .MAKEFLAGS.
   1332  * Initialize a few modules.
   1333  * Parse the arguments from MAKEFLAGS and the command line.
   1334  */
   1335 static void
   1336 main_Init(int argc, char **argv)
   1337 {
   1338 	struct stat sa;
   1339 	const char *machine;
   1340 	const char *machine_arch;
   1341 	char *syspath = getenv("MAKESYSPATH");
   1342 	struct utsname utsname;
   1343 
   1344 	/* default to writing debug to stderr */
   1345 	opts.debug_file = stderr;
   1346 
   1347 	HashTable_Init(&cached_realpaths);
   1348 
   1349 #ifdef SIGINFO
   1350 	(void)bmake_signal(SIGINFO, siginfo);
   1351 #endif
   1352 
   1353 	InitRandom();
   1354 
   1355 	progname = str_basename(argv[0]);
   1356 
   1357 	UnlimitFiles();
   1358 
   1359 	if (uname(&utsname) == -1) {
   1360 		(void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
   1361 		    strerror(errno));
   1362 		exit(2);
   1363 	}
   1364 
   1365 	/*
   1366 	 * Get the name of this type of MACHINE from utsname
   1367 	 * so we can share an executable for similar machines.
   1368 	 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
   1369 	 *
   1370 	 * Note that both MACHINE and MACHINE_ARCH are decided at
   1371 	 * run-time.
   1372 	 */
   1373 	machine = InitVarMachine(&utsname);
   1374 	machine_arch = InitVarMachineArch();
   1375 
   1376 	myPid = getpid();	/* remember this for vFork() */
   1377 
   1378 	/*
   1379 	 * Just in case MAKEOBJDIR wants us to do something tricky.
   1380 	 */
   1381 	Targ_Init();
   1382 	Var_Init();
   1383 	Var_Set(".MAKE.OS", utsname.sysname, VAR_GLOBAL);
   1384 	Var_Set("MACHINE", machine, VAR_GLOBAL);
   1385 	Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
   1386 #ifdef MAKE_VERSION
   1387 	Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
   1388 #endif
   1389 	Var_Set(".newline", "\n", VAR_GLOBAL); /* handy for :@ loops */
   1390 	/*
   1391 	 * This is the traditional preference for makefiles.
   1392 	 */
   1393 #ifndef MAKEFILE_PREFERENCE_LIST
   1394 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
   1395 #endif
   1396 	Var_Set(MAKE_MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST, VAR_GLOBAL);
   1397 	Var_Set(MAKE_DEPENDFILE, ".depend", VAR_GLOBAL);
   1398 
   1399 	CmdOpts_Init();
   1400 	allPrecious = FALSE;	/* Remove targets when interrupted */
   1401 	deleteOnError = FALSE;	/* Historical default behavior */
   1402 	jobsRunning = FALSE;
   1403 
   1404 	maxJobTokens = opts.maxJobs;
   1405 	ignorePWD = FALSE;
   1406 
   1407 	/*
   1408 	 * Initialize the parsing, directory and variable modules to prepare
   1409 	 * for the reading of inclusion paths and variable settings on the
   1410 	 * command line
   1411 	 */
   1412 
   1413 	/*
   1414 	 * Initialize various variables.
   1415 	 *	MAKE also gets this name, for compatibility
   1416 	 *	.MAKEFLAGS gets set to the empty string just in case.
   1417 	 *	MFLAGS also gets initialized empty, for compatibility.
   1418 	 */
   1419 	Parse_Init();
   1420 	InitVarMake(argv[0]);
   1421 	Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
   1422 	Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL);
   1423 	Var_Set("MFLAGS", "", VAR_GLOBAL);
   1424 	Var_Set(".ALLTARGETS", "", VAR_GLOBAL);
   1425 	/* some makefiles need to know this */
   1426 	Var_Set(MAKE_LEVEL ".ENV", MAKE_LEVEL_ENV, VAR_CMDLINE);
   1427 
   1428 	/* Set some other useful variables. */
   1429 	{
   1430 		char tmp[64], *ep = getenv(MAKE_LEVEL_ENV);
   1431 
   1432 		makelevel = ep != NULL && ep[0] != '\0' ? atoi(ep) : 0;
   1433 		if (makelevel < 0)
   1434 			makelevel = 0;
   1435 		snprintf(tmp, sizeof tmp, "%d", makelevel);
   1436 		Var_Set(MAKE_LEVEL, tmp, VAR_GLOBAL);
   1437 		snprintf(tmp, sizeof tmp, "%u", myPid);
   1438 		Var_Set(".MAKE.PID", tmp, VAR_GLOBAL);
   1439 		snprintf(tmp, sizeof tmp, "%u", getppid());
   1440 		Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL);
   1441 		snprintf(tmp, sizeof tmp, "%u", getuid());
   1442 		Var_Set(".MAKE.UID", tmp, VAR_GLOBAL);
   1443 		snprintf(tmp, sizeof tmp, "%u", getgid());
   1444 		Var_Set(".MAKE.GID", tmp, VAR_GLOBAL);
   1445 	}
   1446 	if (makelevel > 0) {
   1447 		char pn[1024];
   1448 		snprintf(pn, sizeof pn, "%s[%d]", progname, makelevel);
   1449 		progname = bmake_strdup(pn);
   1450 	}
   1451 
   1452 #ifdef USE_META
   1453 	meta_init();
   1454 #endif
   1455 	Dir_Init();
   1456 
   1457 	/*
   1458 	 * First snag any flags out of the MAKE environment variable.
   1459 	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
   1460 	 * in a different format).
   1461 	 */
   1462 #ifdef POSIX
   1463 	{
   1464 		char *p1 = explode(getenv("MAKEFLAGS"));
   1465 		Main_ParseArgLine(p1);
   1466 		free(p1);
   1467 	}
   1468 #else
   1469 	Main_ParseArgLine(getenv("MAKE"));
   1470 #endif
   1471 
   1472 	/*
   1473 	 * Find where we are (now).
   1474 	 * We take care of PWD for the automounter below...
   1475 	 */
   1476 	if (getcwd(curdir, MAXPATHLEN) == NULL) {
   1477 		(void)fprintf(stderr, "%s: getcwd: %s.\n",
   1478 		    progname, strerror(errno));
   1479 		exit(2);
   1480 	}
   1481 
   1482 	MainParseArgs(argc, argv);
   1483 
   1484 	if (opts.enterFlag)
   1485 		printf("%s: Entering directory `%s'\n", progname, curdir);
   1486 
   1487 	/*
   1488 	 * Verify that cwd is sane.
   1489 	 */
   1490 	if (stat(curdir, &sa) == -1) {
   1491 		(void)fprintf(stderr, "%s: %s: %s.\n",
   1492 		    progname, curdir, strerror(errno));
   1493 		exit(2);
   1494 	}
   1495 
   1496 #ifndef NO_PWD_OVERRIDE
   1497 	HandlePWD(&sa);
   1498 #endif
   1499 	Var_Set(".CURDIR", curdir, VAR_GLOBAL);
   1500 
   1501 	InitObjdir(machine, machine_arch);
   1502 
   1503 	/*
   1504 	 * Initialize archive, target and suffix modules in preparation for
   1505 	 * parsing the makefile(s)
   1506 	 */
   1507 	Arch_Init();
   1508 	Suff_Init();
   1509 	Trace_Init(tracefile);
   1510 
   1511 	defaultNode = NULL;
   1512 	(void)time(&now);
   1513 
   1514 	Trace_Log(MAKESTART, NULL);
   1515 
   1516 	InitVarTargets();
   1517 
   1518 	InitDefSysIncPath(syspath);
   1519 }
   1520 
   1521 /*
   1522  * Read the system makefile followed by either makefile, Makefile or the
   1523  * files given by the -f option. Exit on parse errors.
   1524  */
   1525 static void
   1526 main_ReadFiles(void)
   1527 {
   1528 
   1529 	if (!opts.noBuiltins)
   1530 		ReadBuiltinRules();
   1531 
   1532 	if (!Lst_IsEmpty(&opts.makefiles))
   1533 		ReadAllMakefiles(&opts.makefiles);
   1534 	else
   1535 		ReadFirstDefaultMakefile();
   1536 }
   1537 
   1538 /* Compute the dependency graph. */
   1539 static void
   1540 main_PrepareMaking(void)
   1541 {
   1542 	/* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
   1543 	if (!opts.noBuiltins || opts.printVars == PVM_NONE) {
   1544 		(void)Var_Subst("${.MAKE.DEPENDFILE}",
   1545 		    VAR_CMDLINE, VARE_WANTRES, &makeDependfile);
   1546 		if (makeDependfile[0] != '\0') {
   1547 			/* TODO: handle errors */
   1548 			doing_depend = TRUE;
   1549 			(void)ReadMakefile(makeDependfile);
   1550 			doing_depend = FALSE;
   1551 		}
   1552 	}
   1553 
   1554 	if (enterFlagObj)
   1555 		printf("%s: Entering directory `%s'\n", progname, objdir);
   1556 
   1557 	MakeMode();
   1558 
   1559 	{
   1560 		FStr makeflags = Var_Value(MAKEFLAGS, VAR_GLOBAL);
   1561 		Var_Append("MFLAGS", makeflags.str, VAR_GLOBAL);
   1562 		FStr_Done(&makeflags);
   1563 	}
   1564 
   1565 	InitMaxJobs();
   1566 
   1567 	/*
   1568 	 * Be compatible if the user did not specify -j and did not explicitly
   1569 	 * turn compatibility on.
   1570 	 */
   1571 	if (!opts.compatMake && !forceJobs)
   1572 		opts.compatMake = TRUE;
   1573 
   1574 	if (!opts.compatMake)
   1575 		Job_ServerStart(maxJobTokens, jp_0, jp_1);
   1576 	DEBUG5(JOB, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
   1577 	    jp_0, jp_1, opts.maxJobs, maxJobTokens, opts.compatMake ? 1 : 0);
   1578 
   1579 	if (opts.printVars == PVM_NONE)
   1580 		Main_ExportMAKEFLAGS(TRUE);	/* initial export */
   1581 
   1582 	InitVpath();
   1583 
   1584 	/*
   1585 	 * Now that all search paths have been read for suffixes et al, it's
   1586 	 * time to add the default search path to their lists...
   1587 	 */
   1588 	Suff_DoPaths();
   1589 
   1590 	/*
   1591 	 * Propagate attributes through :: dependency lists.
   1592 	 */
   1593 	Targ_Propagate();
   1594 
   1595 	/* print the initial graph, if the user requested it */
   1596 	if (DEBUG(GRAPH1))
   1597 		Targ_PrintGraph(1);
   1598 }
   1599 
   1600 /*
   1601  * Make the targets.
   1602  * If the -v or -V options are given, print variables instead.
   1603  * Return whether any of the targets is out-of-date.
   1604  */
   1605 static Boolean
   1606 main_Run(void)
   1607 {
   1608 	if (opts.printVars != PVM_NONE) {
   1609 		/* print the values of any variables requested by the user */
   1610 		doPrintVars();
   1611 		return FALSE;
   1612 	} else {
   1613 		return runTargets();
   1614 	}
   1615 }
   1616 
   1617 /* Clean up after making the targets. */
   1618 static void
   1619 main_CleanUp(void)
   1620 {
   1621 #ifdef CLEANUP
   1622 	Lst_DoneCall(&opts.variables, free);
   1623 	/*
   1624 	 * Don't free the actual strings from opts.makefiles, they may be
   1625 	 * used in GNodes.
   1626 	 */
   1627 	Lst_Done(&opts.makefiles);
   1628 	Lst_DoneCall(&opts.create, free);
   1629 #endif
   1630 
   1631 	/* print the graph now it's been processed if the user requested it */
   1632 	if (DEBUG(GRAPH2))
   1633 		Targ_PrintGraph(2);
   1634 
   1635 	Trace_Log(MAKEEND, NULL);
   1636 
   1637 	if (enterFlagObj)
   1638 		printf("%s: Leaving directory `%s'\n", progname, objdir);
   1639 	if (opts.enterFlag)
   1640 		printf("%s: Leaving directory `%s'\n", progname, curdir);
   1641 
   1642 #ifdef USE_META
   1643 	meta_finish();
   1644 #endif
   1645 	Suff_End();
   1646 	Targ_End();
   1647 	Arch_End();
   1648 	Var_End();
   1649 	Parse_End();
   1650 	Dir_End();
   1651 	Job_End();
   1652 	Trace_End();
   1653 }
   1654 
   1655 /* Determine the exit code. */
   1656 static int
   1657 main_Exit(Boolean outOfDate)
   1658 {
   1659 	if (opts.strict && (main_errors > 0 || Parse_GetFatals() > 0))
   1660 		return 2;	/* Not 1 so -q can distinguish error */
   1661 	return outOfDate ? 1 : 0;
   1662 }
   1663 
   1664 int
   1665 main(int argc, char **argv)
   1666 {
   1667 	Boolean outOfDate;
   1668 
   1669 	main_Init(argc, argv);
   1670 	main_ReadFiles();
   1671 	main_PrepareMaking();
   1672 	outOfDate = main_Run();
   1673 	main_CleanUp();
   1674 	return main_Exit(outOfDate);
   1675 }
   1676 
   1677 /*
   1678  * Open and parse the given makefile, with all its side effects.
   1679  *
   1680  * Results:
   1681  *	0 if ok. -1 if couldn't open file.
   1682  */
   1683 static int
   1684 ReadMakefile(const char *fname)
   1685 {
   1686 	int fd;
   1687 	char *name, *path = NULL;
   1688 
   1689 	if (strcmp(fname, "-") == 0) {
   1690 		Parse_File(NULL /*stdin*/, -1);
   1691 		Var_Set("MAKEFILE", "", VAR_INTERNAL);
   1692 	} else {
   1693 		/* if we've chdir'd, rebuild the path name */
   1694 		if (strcmp(curdir, objdir) != 0 && *fname != '/') {
   1695 			path = str_concat3(curdir, "/", fname);
   1696 			fd = open(path, O_RDONLY);
   1697 			if (fd != -1) {
   1698 				fname = path;
   1699 				goto found;
   1700 			}
   1701 			free(path);
   1702 
   1703 			/* If curdir failed, try objdir (ala .depend) */
   1704 			path = str_concat3(objdir, "/", fname);
   1705 			fd = open(path, O_RDONLY);
   1706 			if (fd != -1) {
   1707 				fname = path;
   1708 				goto found;
   1709 			}
   1710 		} else {
   1711 			fd = open(fname, O_RDONLY);
   1712 			if (fd != -1)
   1713 				goto found;
   1714 		}
   1715 		/* look in -I and system include directories. */
   1716 		name = Dir_FindFile(fname, parseIncPath);
   1717 		if (name == NULL) {
   1718 			SearchPath *sysInc = Lst_IsEmpty(&sysIncPath->dirs)
   1719 					     ? defSysIncPath : sysIncPath;
   1720 			name = Dir_FindFile(fname, sysInc);
   1721 		}
   1722 		if (name == NULL || (fd = open(name, O_RDONLY)) == -1) {
   1723 			free(name);
   1724 			free(path);
   1725 			return -1;
   1726 		}
   1727 		fname = name;
   1728 		/*
   1729 		 * set the MAKEFILE variable desired by System V fans -- the
   1730 		 * placement of the setting here means it gets set to the last
   1731 		 * makefile specified, as it is set by SysV make.
   1732 		 */
   1733 found:
   1734 		if (!doing_depend)
   1735 			Var_Set("MAKEFILE", fname, VAR_INTERNAL);
   1736 		Parse_File(fname, fd);
   1737 	}
   1738 	free(path);
   1739 	return 0;
   1740 }
   1741 
   1742 /*
   1743  * Cmd_Exec --
   1744  *	Execute the command in cmd, and return the output of that command
   1745  *	in a string.  In the output, newlines are replaced with spaces.
   1746  *
   1747  * Results:
   1748  *	A string containing the output of the command, or the empty string.
   1749  *	*errfmt returns a format string describing the command failure,
   1750  *	if any, using a single %s conversion specification.
   1751  *
   1752  * Side Effects:
   1753  *	The string must be freed by the caller.
   1754  */
   1755 char *
   1756 Cmd_Exec(const char *cmd, const char **errfmt)
   1757 {
   1758 	const char *args[4];	/* Args for invoking the shell */
   1759 	int pipefds[2];
   1760 	int cpid;		/* Child PID */
   1761 	int pid;		/* PID from wait() */
   1762 	int status;		/* command exit status */
   1763 	Buffer buf;		/* buffer to store the result */
   1764 	ssize_t bytes_read;
   1765 	char *res;		/* result */
   1766 	size_t res_len;
   1767 	char *cp;
   1768 	int savederr;		/* saved errno */
   1769 
   1770 	*errfmt = NULL;
   1771 
   1772 	if (shellName == NULL)
   1773 		Shell_Init();
   1774 	/*
   1775 	 * Set up arguments for shell
   1776 	 */
   1777 	args[0] = shellName;
   1778 	args[1] = "-c";
   1779 	args[2] = cmd;
   1780 	args[3] = NULL;
   1781 
   1782 	/*
   1783 	 * Open a pipe for fetching its output
   1784 	 */
   1785 	if (pipe(pipefds) == -1) {
   1786 		*errfmt = "Couldn't create pipe for \"%s\"";
   1787 		goto bad;
   1788 	}
   1789 
   1790 	Var_ReexportVars();
   1791 
   1792 	/*
   1793 	 * Fork
   1794 	 */
   1795 	switch (cpid = vFork()) {
   1796 	case 0:
   1797 		(void)close(pipefds[0]); /* Close input side of pipe */
   1798 
   1799 		/*
   1800 		 * Duplicate the output stream to the shell's output, then
   1801 		 * shut the extra thing down. Note we don't fetch the error
   1802 		 * stream...why not? Why?
   1803 		 */
   1804 		(void)dup2(pipefds[1], 1);
   1805 		(void)close(pipefds[1]);
   1806 
   1807 		(void)execv(shellPath, UNCONST(args));
   1808 		_exit(1);
   1809 		/*NOTREACHED*/
   1810 
   1811 	case -1:
   1812 		*errfmt = "Couldn't exec \"%s\"";
   1813 		goto bad;
   1814 
   1815 	default:
   1816 		(void)close(pipefds[1]); /* No need for the writing half */
   1817 
   1818 		savederr = 0;
   1819 		Buf_Init(&buf);
   1820 
   1821 		do {
   1822 			char result[BUFSIZ];
   1823 			bytes_read = read(pipefds[0], result, sizeof result);
   1824 			if (bytes_read > 0)
   1825 				Buf_AddBytes(&buf, result, (size_t)bytes_read);
   1826 		} while (bytes_read > 0 ||
   1827 			 (bytes_read == -1 && errno == EINTR));
   1828 		if (bytes_read == -1)
   1829 			savederr = errno;
   1830 
   1831 		(void)close(pipefds[0]); /* Close the input side of the pipe. */
   1832 
   1833 		/* Wait for the process to exit. */
   1834 		while ((pid = waitpid(cpid, &status, 0)) != cpid && pid >= 0)
   1835 			JobReapChild(pid, status, FALSE);
   1836 
   1837 		res_len = buf.len;
   1838 		res = Buf_DoneData(&buf);
   1839 
   1840 		if (savederr != 0)
   1841 			*errfmt = "Couldn't read shell's output for \"%s\"";
   1842 
   1843 		if (WIFSIGNALED(status))
   1844 			*errfmt = "\"%s\" exited on a signal";
   1845 		else if (WEXITSTATUS(status) != 0)
   1846 			*errfmt = "\"%s\" returned non-zero status";
   1847 
   1848 		/* Convert newlines to spaces.  A final newline is just stripped */
   1849 		if (res_len > 0 && res[res_len - 1] == '\n')
   1850 			res[res_len - 1] = '\0';
   1851 		for (cp = res; *cp != '\0'; cp++)
   1852 			if (*cp == '\n')
   1853 				*cp = ' ';
   1854 		break;
   1855 	}
   1856 	return res;
   1857 bad:
   1858 	return bmake_strdup("");
   1859 }
   1860 
   1861 /*
   1862  * Print a printf-style error message.
   1863  *
   1864  * In default mode, this error message has no consequences, in particular it
   1865  * does not affect the exit status.  Only in lint mode (-dL) it does.
   1866  */
   1867 void
   1868 Error(const char *fmt, ...)
   1869 {
   1870 	va_list ap;
   1871 	FILE *err_file;
   1872 
   1873 	err_file = opts.debug_file;
   1874 	if (err_file == stdout)
   1875 		err_file = stderr;
   1876 	(void)fflush(stdout);
   1877 	for (;;) {
   1878 		va_start(ap, fmt);
   1879 		fprintf(err_file, "%s: ", progname);
   1880 		(void)vfprintf(err_file, fmt, ap);
   1881 		va_end(ap);
   1882 		(void)fprintf(err_file, "\n");
   1883 		(void)fflush(err_file);
   1884 		if (err_file == stderr)
   1885 			break;
   1886 		err_file = stderr;
   1887 	}
   1888 	main_errors++;
   1889 }
   1890 
   1891 /*
   1892  * Wait for any running jobs to finish, then produce an error message,
   1893  * finally exit immediately.
   1894  *
   1895  * Exiting immediately differs from Parse_Error, which exits only after the
   1896  * current top-level makefile has been parsed completely.
   1897  */
   1898 void
   1899 Fatal(const char *fmt, ...)
   1900 {
   1901 	va_list ap;
   1902 
   1903 	if (jobsRunning)
   1904 		Job_Wait();
   1905 
   1906 	(void)fflush(stdout);
   1907 	va_start(ap, fmt);
   1908 	(void)vfprintf(stderr, fmt, ap);
   1909 	va_end(ap);
   1910 	(void)fprintf(stderr, "\n");
   1911 	(void)fflush(stderr);
   1912 
   1913 	PrintOnError(NULL, NULL);
   1914 
   1915 	if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
   1916 		Targ_PrintGraph(2);
   1917 	Trace_Log(MAKEERROR, NULL);
   1918 	exit(2);		/* Not 1 so -q can distinguish error */
   1919 }
   1920 
   1921 /*
   1922  * Major exception once jobs are being created.
   1923  * Kills all jobs, prints a message and exits.
   1924  */
   1925 void
   1926 Punt(const char *fmt, ...)
   1927 {
   1928 	va_list ap;
   1929 
   1930 	va_start(ap, fmt);
   1931 	(void)fflush(stdout);
   1932 	(void)fprintf(stderr, "%s: ", progname);
   1933 	(void)vfprintf(stderr, fmt, ap);
   1934 	va_end(ap);
   1935 	(void)fprintf(stderr, "\n");
   1936 	(void)fflush(stderr);
   1937 
   1938 	PrintOnError(NULL, NULL);
   1939 
   1940 	DieHorribly();
   1941 }
   1942 
   1943 /* Exit without giving a message. */
   1944 void
   1945 DieHorribly(void)
   1946 {
   1947 	if (jobsRunning)
   1948 		Job_AbortAll();
   1949 	if (DEBUG(GRAPH2))
   1950 		Targ_PrintGraph(2);
   1951 	Trace_Log(MAKEERROR, NULL);
   1952 	exit(2);		/* Not 1 so -q can distinguish error */
   1953 }
   1954 
   1955 /*
   1956  * Called when aborting due to errors in child shell to signal abnormal exit.
   1957  * The program exits.
   1958  * Errors is the number of errors encountered in Make_Make.
   1959  */
   1960 void
   1961 Finish(int errs)
   1962 {
   1963 	if (shouldDieQuietly(NULL, -1))
   1964 		exit(2);
   1965 	Fatal("%d error%s", errs, errs == 1 ? "" : "s");
   1966 }
   1967 
   1968 /*
   1969  * eunlink --
   1970  *	Remove a file carefully, avoiding directories.
   1971  */
   1972 int
   1973 eunlink(const char *file)
   1974 {
   1975 	struct stat st;
   1976 
   1977 	if (lstat(file, &st) == -1)
   1978 		return -1;
   1979 
   1980 	if (S_ISDIR(st.st_mode)) {
   1981 		errno = EISDIR;
   1982 		return -1;
   1983 	}
   1984 	return unlink(file);
   1985 }
   1986 
   1987 static void
   1988 write_all(int fd, const void *data, size_t n)
   1989 {
   1990 	const char *mem = data;
   1991 
   1992 	while (n > 0) {
   1993 		ssize_t written = write(fd, mem, n);
   1994 		if (written == -1 && errno == EAGAIN)
   1995 			continue;
   1996 		if (written == -1)
   1997 			break;
   1998 		mem += written;
   1999 		n -= (size_t)written;
   2000 	}
   2001 }
   2002 
   2003 /*
   2004  * execDie --
   2005  *	Print why exec failed, avoiding stdio.
   2006  */
   2007 void MAKE_ATTR_DEAD
   2008 execDie(const char *af, const char *av)
   2009 {
   2010 	Buffer buf;
   2011 
   2012 	Buf_Init(&buf);
   2013 	Buf_AddStr(&buf, progname);
   2014 	Buf_AddStr(&buf, ": ");
   2015 	Buf_AddStr(&buf, af);
   2016 	Buf_AddStr(&buf, "(");
   2017 	Buf_AddStr(&buf, av);
   2018 	Buf_AddStr(&buf, ") failed (");
   2019 	Buf_AddStr(&buf, strerror(errno));
   2020 	Buf_AddStr(&buf, ")\n");
   2021 
   2022 	write_all(STDERR_FILENO, buf.data, buf.len);
   2023 
   2024 	Buf_Done(&buf);
   2025 	_exit(1);
   2026 }
   2027 
   2028 /* purge any relative paths */
   2029 static void
   2030 purge_relative_cached_realpaths(void)
   2031 {
   2032 	HashEntry *he, *nhe;
   2033 	HashIter hi;
   2034 
   2035 	HashIter_Init(&hi, &cached_realpaths);
   2036 	he = HashIter_Next(&hi);
   2037 	while (he != NULL) {
   2038 		nhe = HashIter_Next(&hi);
   2039 		if (he->key[0] != '/') {
   2040 			DEBUG1(DIR, "cached_realpath: purging %s\n", he->key);
   2041 			HashTable_DeleteEntry(&cached_realpaths, he);
   2042 			/* XXX: What about the allocated he->value? Either
   2043 			 * free them or document why they cannot be freed. */
   2044 		}
   2045 		he = nhe;
   2046 	}
   2047 }
   2048 
   2049 char *
   2050 cached_realpath(const char *pathname, char *resolved)
   2051 {
   2052 	const char *rp;
   2053 
   2054 	if (pathname == NULL || pathname[0] == '\0')
   2055 		return NULL;
   2056 
   2057 	rp = HashTable_FindValue(&cached_realpaths, pathname);
   2058 	if (rp != NULL) {
   2059 		/* a hit */
   2060 		strncpy(resolved, rp, MAXPATHLEN);
   2061 		resolved[MAXPATHLEN - 1] = '\0';
   2062 		return resolved;
   2063 	}
   2064 
   2065 	rp = realpath(pathname, resolved);
   2066 	if (rp != NULL) {
   2067 		HashTable_Set(&cached_realpaths, pathname, bmake_strdup(rp));
   2068 		DEBUG2(DIR, "cached_realpath: %s -> %s\n", pathname, rp);
   2069 		return resolved;
   2070 	}
   2071 
   2072 	/* should we negative-cache? */
   2073 	return NULL;
   2074 }
   2075 
   2076 /*
   2077  * Return true if we should die without noise.
   2078  * For example our failing child was a sub-make or failure happened elsewhere.
   2079  */
   2080 Boolean
   2081 shouldDieQuietly(GNode *gn, int bf)
   2082 {
   2083 	static int quietly = -1;
   2084 
   2085 	if (quietly < 0) {
   2086 		if (DEBUG(JOB) || !GetBooleanVar(".MAKE.DIE_QUIETLY", TRUE))
   2087 			quietly = 0;
   2088 		else if (bf >= 0)
   2089 			quietly = bf;
   2090 		else
   2091 			quietly = (gn != NULL && (gn->type & OP_MAKE)) ? 1 : 0;
   2092 	}
   2093 	return quietly != 0;
   2094 }
   2095 
   2096 static void
   2097 SetErrorVars(GNode *gn)
   2098 {
   2099 	StringListNode *ln;
   2100 
   2101 	/*
   2102 	 * We can print this even if there is no .ERROR target.
   2103 	 */
   2104 	Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL);
   2105 	Var_Delete(".ERROR_CMD", VAR_GLOBAL);
   2106 
   2107 	for (ln = gn->commands.first; ln != NULL; ln = ln->next) {
   2108 		const char *cmd = ln->datum;
   2109 
   2110 		if (cmd == NULL)
   2111 			break;
   2112 		Var_Append(".ERROR_CMD", cmd, VAR_GLOBAL);
   2113 	}
   2114 }
   2115 
   2116 /*
   2117  * Print some helpful information in case of an error.
   2118  * The caller should exit soon after calling this function.
   2119  */
   2120 void
   2121 PrintOnError(GNode *gn, const char *msg)
   2122 {
   2123 	static GNode *errorNode = NULL;
   2124 
   2125 	if (DEBUG(HASH)) {
   2126 		Targ_Stats();
   2127 		Var_Stats();
   2128 	}
   2129 
   2130 	if (errorNode != NULL)
   2131 		return;		/* we've been here! */
   2132 
   2133 	if (msg != NULL)
   2134 		printf("%s", msg);
   2135 	printf("\n%s: stopped in %s\n", progname, curdir);
   2136 
   2137 	/* we generally want to keep quiet if a sub-make died */
   2138 	if (shouldDieQuietly(gn, -1))
   2139 		return;
   2140 
   2141 	if (gn != NULL)
   2142 		SetErrorVars(gn);
   2143 
   2144 	{
   2145 		char *errorVarsValues;
   2146 		(void)Var_Subst("${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
   2147 				VAR_GLOBAL, VARE_WANTRES, &errorVarsValues);
   2148 		/* TODO: handle errors */
   2149 		printf("%s", errorVarsValues);
   2150 		free(errorVarsValues);
   2151 	}
   2152 
   2153 	fflush(stdout);
   2154 
   2155 	/*
   2156 	 * Finally, see if there is a .ERROR target, and run it if so.
   2157 	 */
   2158 	errorNode = Targ_FindNode(".ERROR");
   2159 	if (errorNode != NULL) {
   2160 		errorNode->type |= OP_SPECIAL;
   2161 		Compat_Make(errorNode, errorNode);
   2162 	}
   2163 }
   2164 
   2165 void
   2166 Main_ExportMAKEFLAGS(Boolean first)
   2167 {
   2168 	static Boolean once = TRUE;
   2169 	const char *expr;
   2170 	char *s;
   2171 
   2172 	if (once != first)
   2173 		return;
   2174 	once = FALSE;
   2175 
   2176 	expr = "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}";
   2177 	(void)Var_Subst(expr, VAR_CMDLINE, VARE_WANTRES, &s);
   2178 	/* TODO: handle errors */
   2179 	if (s[0] != '\0') {
   2180 #ifdef POSIX
   2181 		setenv("MAKEFLAGS", s, 1);
   2182 #else
   2183 		setenv("MAKE", s, 1);
   2184 #endif
   2185 	}
   2186 }
   2187 
   2188 char *
   2189 getTmpdir(void)
   2190 {
   2191 	static char *tmpdir = NULL;
   2192 	struct stat st;
   2193 
   2194 	if (tmpdir != NULL)
   2195 		return tmpdir;
   2196 
   2197 	/* Honor $TMPDIR but only if it is valid. Ensure it ends with '/'. */
   2198 	(void)Var_Subst("${TMPDIR:tA:U" _PATH_TMP "}/",
   2199 	    VAR_GLOBAL, VARE_WANTRES, &tmpdir);
   2200 	/* TODO: handle errors */
   2201 
   2202 	if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
   2203 		free(tmpdir);
   2204 		tmpdir = bmake_strdup(_PATH_TMP);
   2205 	}
   2206 	return tmpdir;
   2207 }
   2208 
   2209 /*
   2210  * Create and open a temp file using "pattern".
   2211  * If out_fname is provided, set it to a copy of the filename created.
   2212  * Otherwise unlink the file once open.
   2213  */
   2214 int
   2215 mkTempFile(const char *pattern, char **out_fname)
   2216 {
   2217 	static char *tmpdir = NULL;
   2218 	char tfile[MAXPATHLEN];
   2219 	int fd;
   2220 
   2221 	if (pattern == NULL)
   2222 		pattern = TMPPAT;
   2223 	if (tmpdir == NULL)
   2224 		tmpdir = getTmpdir();
   2225 	if (pattern[0] == '/') {
   2226 		snprintf(tfile, sizeof tfile, "%s", pattern);
   2227 	} else {
   2228 		snprintf(tfile, sizeof tfile, "%s%s", tmpdir, pattern);
   2229 	}
   2230 	if ((fd = mkstemp(tfile)) < 0)
   2231 		Punt("Could not create temporary file %s: %s", tfile,
   2232 		    strerror(errno));
   2233 	if (out_fname != NULL) {
   2234 		*out_fname = bmake_strdup(tfile);
   2235 	} else {
   2236 		unlink(tfile);	/* we just want the descriptor */
   2237 	}
   2238 	return fd;
   2239 }
   2240 
   2241 /*
   2242  * Convert a string representation of a boolean into a boolean value.
   2243  * Anything that looks like "No", "False", "Off", "0" etc. is FALSE,
   2244  * the empty string is the fallback, everything else is TRUE.
   2245  */
   2246 Boolean
   2247 ParseBoolean(const char *s, Boolean fallback)
   2248 {
   2249 	char ch = ch_tolower(s[0]);
   2250 	if (ch == '\0')
   2251 		return fallback;
   2252 	if (ch == '0' || ch == 'f' || ch == 'n')
   2253 		return FALSE;
   2254 	if (ch == 'o')
   2255 		return ch_tolower(s[1]) != 'f';
   2256 	return TRUE;
   2257 }
   2258