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