Home | History | Annotate | Line # | Download | only in make
main.c revision 1.508
      1 /*	$NetBSD: main.c,v 1.508 2020/12/31 17:39:36 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	Parse and process command line arguments from
     77  *				a single string.  Used to implement the
     78  *				special targets .MFLAGS and .MAKEFLAGS.
     79  *
     80  *	Error			Print a tagged error message.
     81  *
     82  *	Fatal			Print an error message and exit.
     83  *
     84  *	Punt			Abort all jobs and exit with a message.
     85  *
     86  *	Finish			Finish things up by printing the number of
     87  *				errors which occurred, and exit.
     88  */
     89 
     90 #include <sys/types.h>
     91 #include <sys/time.h>
     92 #include <sys/param.h>
     93 #include <sys/resource.h>
     94 #include <sys/stat.h>
     95 #ifdef MAKE_NATIVE
     96 #include <sys/sysctl.h>
     97 #endif
     98 #include <sys/utsname.h>
     99 #include <sys/wait.h>
    100 
    101 #include <errno.h>
    102 #include <signal.h>
    103 #include <stdarg.h>
    104 #include <time.h>
    105 
    106 #include "make.h"
    107 #include "dir.h"
    108 #include "job.h"
    109 #include "pathnames.h"
    110 #include "trace.h"
    111 
    112 /*	"@(#)main.c	8.3 (Berkeley) 3/19/94"	*/
    113 MAKE_RCSID("$NetBSD: main.c,v 1.508 2020/12/31 17:39:36 rillig Exp $");
    114 #if defined(MAKE_NATIVE) && !defined(lint)
    115 __COPYRIGHT("@(#) Copyright (c) 1988, 1989, 1990, 1993 "
    116 	    "The Regents of the University of California.  "
    117 	    "All rights reserved.");
    118 #endif
    119 
    120 CmdOpts opts;
    121 time_t now;			/* Time at start of make */
    122 GNode *defaultNode;		/* .DEFAULT node */
    123 Boolean allPrecious;		/* .PRECIOUS given on line by itself */
    124 Boolean deleteOnError;		/* .DELETE_ON_ERROR: set */
    125 
    126 static int maxJobTokens;	/* -j argument */
    127 Boolean enterFlagObj;		/* -w and objdir != srcdir */
    128 
    129 static int jp_0 = -1, jp_1 = -1; /* ends of parent job pipe */
    130 Boolean doing_depend;		/* Set while reading .depend */
    131 static Boolean jobsRunning;	/* TRUE if the jobs might be running */
    132 static const char *tracefile;
    133 static int ReadMakefile(const char *);
    134 static void purge_relative_cached_realpaths(void);
    135 
    136 static Boolean ignorePWD;	/* if we use -C, PWD is meaningless */
    137 static char objdir[MAXPATHLEN + 1]; /* where we chdir'ed to */
    138 char curdir[MAXPATHLEN + 1];	/* Startup directory */
    139 const char *progname;
    140 char *makeDependfile;
    141 pid_t myPid;
    142 int makelevel;
    143 
    144 Boolean forceJobs = FALSE;
    145 static int main_errors = 0;
    146 static HashTable cached_realpaths;
    147 
    148 /*
    149  * For compatibility with the POSIX version of MAKEFLAGS that includes
    150  * all the options without '-', convert 'flags' to '-f -l -a -g -s'.
    151  */
    152 static char *
    153 explode(const char *flags)
    154 {
    155 	size_t len;
    156 	char *nf, *st;
    157 	const char *f;
    158 
    159 	if (flags == NULL)
    160 		return NULL;
    161 
    162 	for (f = flags; *f; f++)
    163 		if (!ch_isalpha(*f))
    164 			break;
    165 
    166 	if (*f != '\0')
    167 		return bmake_strdup(flags);
    168 
    169 	len = strlen(flags);
    170 	st = nf = bmake_malloc(len * 3 + 1);
    171 	while (*flags != '\0') {
    172 		*nf++ = '-';
    173 		*nf++ = *flags++;
    174 		*nf++ = ' ';
    175 	}
    176 	*nf = '\0';
    177 	return st;
    178 }
    179 
    180 /*
    181  * usage --
    182  *	exit with usage message
    183  */
    184 MAKE_ATTR_DEAD static void
    185 usage(void)
    186 {
    187 	size_t prognameLen = strcspn(progname, "[");
    188 
    189 	(void)fprintf(stderr,
    190 "usage: %.*s [-BeikNnqrSstWwX]\n"
    191 "            [-C directory] [-D variable] [-d flags] [-f makefile]\n"
    192 "            [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n"
    193 "            [-V variable] [-v variable] [variable=value] [target ...]\n",
    194 	    (int)prognameLen, progname);
    195 	exit(2);
    196 }
    197 
    198 static void
    199 parse_debug_option_F(const char *modules)
    200 {
    201 	const char *mode;
    202 	size_t len;
    203 	char *fname;
    204 
    205 	if (opts.debug_file != stdout && opts.debug_file != stderr)
    206 		fclose(opts.debug_file);
    207 
    208 	if (*modules == '+') {
    209 		modules++;
    210 		mode = "a";
    211 	} else
    212 		mode = "w";
    213 
    214 	if (strcmp(modules, "stdout") == 0) {
    215 		opts.debug_file = stdout;
    216 		return;
    217 	}
    218 	if (strcmp(modules, "stderr") == 0) {
    219 		opts.debug_file = stderr;
    220 		return;
    221 	}
    222 
    223 	len = strlen(modules);
    224 	fname = bmake_malloc(len + 20);
    225 	memcpy(fname, modules, len + 1);
    226 
    227 	/* Let the filename be modified by the pid */
    228 	if (strcmp(fname + len - 3, ".%d") == 0)
    229 		snprintf(fname + len - 2, 20, "%d", getpid());
    230 
    231 	opts.debug_file = fopen(fname, mode);
    232 	if (opts.debug_file == NULL) {
    233 		fprintf(stderr, "Cannot open debug file %s\n",
    234 		    fname);
    235 		usage();
    236 	}
    237 	free(fname);
    238 }
    239 
    240 static void
    241 parse_debug_options(const char *argvalue)
    242 {
    243 	const char *modules;
    244 	DebugFlags debug = opts.debug;
    245 
    246 	for (modules = argvalue; *modules; ++modules) {
    247 		switch (*modules) {
    248 		case '0':	/* undocumented, only intended for tests */
    249 			debug = DEBUG_NONE;
    250 			break;
    251 		case 'A':
    252 			debug = DEBUG_ALL;
    253 			break;
    254 		case 'a':
    255 			debug |= DEBUG_ARCH;
    256 			break;
    257 		case 'C':
    258 			debug |= DEBUG_CWD;
    259 			break;
    260 		case 'c':
    261 			debug |= DEBUG_COND;
    262 			break;
    263 		case 'd':
    264 			debug |= DEBUG_DIR;
    265 			break;
    266 		case 'e':
    267 			debug |= DEBUG_ERROR;
    268 			break;
    269 		case 'f':
    270 			debug |= DEBUG_FOR;
    271 			break;
    272 		case 'g':
    273 			if (modules[1] == '1') {
    274 				debug |= DEBUG_GRAPH1;
    275 				modules++;
    276 			} else if (modules[1] == '2') {
    277 				debug |= DEBUG_GRAPH2;
    278 				modules++;
    279 			} else if (modules[1] == '3') {
    280 				debug |= DEBUG_GRAPH3;
    281 				modules++;
    282 			}
    283 			break;
    284 		case 'h':
    285 			debug |= DEBUG_HASH;
    286 			break;
    287 		case 'j':
    288 			debug |= DEBUG_JOB;
    289 			break;
    290 		case 'L':
    291 			opts.strict = TRUE;
    292 			break;
    293 		case 'l':
    294 			debug |= DEBUG_LOUD;
    295 			break;
    296 		case 'M':
    297 			debug |= DEBUG_META;
    298 			break;
    299 		case 'm':
    300 			debug |= DEBUG_MAKE;
    301 			break;
    302 		case 'n':
    303 			debug |= DEBUG_SCRIPT;
    304 			break;
    305 		case 'p':
    306 			debug |= DEBUG_PARSE;
    307 			break;
    308 		case 's':
    309 			debug |= DEBUG_SUFF;
    310 			break;
    311 		case 't':
    312 			debug |= DEBUG_TARG;
    313 			break;
    314 		case 'V':
    315 			opts.debugVflag = TRUE;
    316 			break;
    317 		case 'v':
    318 			debug |= DEBUG_VAR;
    319 			break;
    320 		case 'x':
    321 			debug |= DEBUG_SHELL;
    322 			break;
    323 		case 'F':
    324 			parse_debug_option_F(modules + 1);
    325 			goto debug_setbuf;
    326 		default:
    327 			(void)fprintf(stderr,
    328 			    "%s: illegal argument to d option -- %c\n",
    329 			    progname, *modules);
    330 			usage();
    331 		}
    332 	}
    333 
    334 debug_setbuf:
    335 	opts.debug = debug;
    336 
    337 	/*
    338 	 * Make the debug_file unbuffered, and make
    339 	 * stdout line buffered (unless debugfile == stdout).
    340 	 */
    341 	setvbuf(opts.debug_file, NULL, _IONBF, 0);
    342 	if (opts.debug_file != stdout) {
    343 		setvbuf(stdout, NULL, _IOLBF, 0);
    344 	}
    345 }
    346 
    347 /*
    348  * does path contain any relative components
    349  */
    350 static Boolean
    351 is_relpath(const char *path)
    352 {
    353 	const char *cp;
    354 
    355 	if (path[0] != '/')
    356 		return TRUE;
    357 	cp = path;
    358 	while ((cp = strstr(cp, "/.")) != NULL) {
    359 		cp += 2;
    360 		if (*cp == '.')
    361 			cp++;
    362 		if (cp[0] == '/' || cp[0] == '\0')
    363 			return TRUE;
    364 	}
    365 	return FALSE;
    366 }
    367 
    368 static void
    369 MainParseArgChdir(const char *argvalue)
    370 {
    371 	struct stat sa, sb;
    372 
    373 	if (chdir(argvalue) == -1) {
    374 		(void)fprintf(stderr, "%s: chdir %s: %s\n",
    375 		    progname, argvalue, strerror(errno));
    376 		exit(2);	/* Not 1 so -q can distinguish error */
    377 	}
    378 	if (getcwd(curdir, MAXPATHLEN) == NULL) {
    379 		(void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
    380 		exit(2);
    381 	}
    382 	if (!is_relpath(argvalue) &&
    383 	    stat(argvalue, &sa) != -1 &&
    384 	    stat(curdir, &sb) != -1 &&
    385 	    sa.st_ino == sb.st_ino &&
    386 	    sa.st_dev == sb.st_dev)
    387 		strncpy(curdir, argvalue, MAXPATHLEN);
    388 	ignorePWD = TRUE;
    389 }
    390 
    391 static void
    392 MainParseArgJobsInternal(const char *argvalue)
    393 {
    394 	char end;
    395 	if (sscanf(argvalue, "%d,%d%c", &jp_0, &jp_1, &end) != 2) {
    396 		(void)fprintf(stderr,
    397 		    "%s: internal error -- J option malformed (%s)\n",
    398 		    progname, argvalue);
    399 		usage();
    400 	}
    401 	if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
    402 	    (fcntl(jp_1, F_GETFD, 0) < 0)) {
    403 #if 0
    404 		(void)fprintf(stderr,
    405 		    "%s: ###### warning -- J descriptors were closed!\n",
    406 		    progname);
    407 		exit(2);
    408 #endif
    409 		jp_0 = -1;
    410 		jp_1 = -1;
    411 		opts.compatMake = TRUE;
    412 	} else {
    413 		Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
    414 		Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    415 	}
    416 }
    417 
    418 static void
    419 MainParseArgJobs(const char *argvalue)
    420 {
    421 	char *p;
    422 
    423 	forceJobs = TRUE;
    424 	opts.maxJobs = (int)strtol(argvalue, &p, 0);
    425 	if (*p != '\0' || opts.maxJobs < 1) {
    426 		(void)fprintf(stderr,
    427 		    "%s: illegal argument to -j -- must be positive integer!\n",
    428 		    progname);
    429 		exit(2);	/* Not 1 so -q can distinguish error */
    430 	}
    431 	Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
    432 	Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    433 	Var_Set(".MAKE.JOBS", argvalue, VAR_GLOBAL);
    434 	maxJobTokens = opts.maxJobs;
    435 }
    436 
    437 static void
    438 MainParseArgSysInc(const char *argvalue)
    439 {
    440 	/* look for magic parent directory search string */
    441 	if (strncmp(".../", argvalue, 4) == 0) {
    442 		char *found_path = Dir_FindHereOrAbove(curdir, argvalue + 4);
    443 		if (found_path == NULL)
    444 			return;
    445 		(void)Dir_AddDir(sysIncPath, found_path);
    446 		free(found_path);
    447 	} else {
    448 		(void)Dir_AddDir(sysIncPath, argvalue);
    449 	}
    450 	Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
    451 	Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    452 }
    453 
    454 static Boolean
    455 MainParseArg(char c, const char *argvalue)
    456 {
    457 	switch (c) {
    458 	case '\0':
    459 		break;
    460 	case 'B':
    461 		opts.compatMake = TRUE;
    462 		Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
    463 		Var_Set(MAKE_MODE, "compat", VAR_GLOBAL);
    464 		break;
    465 	case 'C':
    466 		MainParseArgChdir(argvalue);
    467 		break;
    468 	case 'D':
    469 		if (argvalue[0] == '\0') return FALSE;
    470 		Var_Set(argvalue, "1", VAR_GLOBAL);
    471 		Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
    472 		Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    473 		break;
    474 	case 'I':
    475 		Parse_AddIncludeDir(argvalue);
    476 		Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
    477 		Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    478 		break;
    479 	case 'J':
    480 		MainParseArgJobsInternal(argvalue);
    481 		break;
    482 	case 'N':
    483 		opts.noExecute = TRUE;
    484 		opts.noRecursiveExecute = TRUE;
    485 		Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
    486 		break;
    487 	case 'S':
    488 		opts.keepgoing = FALSE;
    489 		Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
    490 		break;
    491 	case 'T':
    492 		tracefile = bmake_strdup(argvalue);
    493 		Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
    494 		Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    495 		break;
    496 	case 'V':
    497 	case 'v':
    498 		opts.printVars = c == 'v' ? PVM_EXPANDED : PVM_UNEXPANDED;
    499 		Lst_Append(&opts.variables, bmake_strdup(argvalue));
    500 		/* XXX: Why always -V? */
    501 		Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
    502 		Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    503 		break;
    504 	case 'W':
    505 		opts.parseWarnFatal = TRUE;
    506 		/* XXX: why no Var_Append? */
    507 		break;
    508 	case 'X':
    509 		opts.varNoExportEnv = TRUE;
    510 		Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
    511 		break;
    512 	case 'd':
    513 		/* If '-d-opts' don't pass to children */
    514 		if (argvalue[0] == '-')
    515 			argvalue++;
    516 		else {
    517 			Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
    518 			Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    519 		}
    520 		parse_debug_options(argvalue);
    521 		break;
    522 	case 'e':
    523 		opts.checkEnvFirst = TRUE;
    524 		Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
    525 		break;
    526 	case 'f':
    527 		Lst_Append(&opts.makefiles, bmake_strdup(argvalue));
    528 		break;
    529 	case 'i':
    530 		opts.ignoreErrors = TRUE;
    531 		Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
    532 		break;
    533 	case 'j':
    534 		MainParseArgJobs(argvalue);
    535 		break;
    536 	case 'k':
    537 		opts.keepgoing = TRUE;
    538 		Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
    539 		break;
    540 	case 'm':
    541 		MainParseArgSysInc(argvalue);
    542 		/* XXX: why no Var_Append? */
    543 		break;
    544 	case 'n':
    545 		opts.noExecute = TRUE;
    546 		Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
    547 		break;
    548 	case 'q':
    549 		opts.queryFlag = TRUE;
    550 		/* Kind of nonsensical, wot? */
    551 		Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
    552 		break;
    553 	case 'r':
    554 		opts.noBuiltins = TRUE;
    555 		Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
    556 		break;
    557 	case 's':
    558 		opts.beSilent = TRUE;
    559 		Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
    560 		break;
    561 	case 't':
    562 		opts.touchFlag = TRUE;
    563 		Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
    564 		break;
    565 	case 'w':
    566 		opts.enterFlag = TRUE;
    567 		Var_Append(MAKEFLAGS, "-w", VAR_GLOBAL);
    568 		break;
    569 	default:
    570 	case '?':
    571 		usage();
    572 	}
    573 	return TRUE;
    574 }
    575 
    576 /*
    577  * Parse the given arguments.  Called from main() and from
    578  * Main_ParseArgLine() when the .MAKEFLAGS target is used.
    579  *
    580  * The arguments must be treated as read-only and will be freed after the
    581  * call.
    582  *
    583  * XXX: Deal with command line overriding .MAKEFLAGS in makefile
    584  */
    585 static void
    586 MainParseArgs(int argc, char **argv)
    587 {
    588 	char c;
    589 	int arginc;
    590 	char *argvalue;
    591 	char *optscan;
    592 	Boolean inOption, dashDash = FALSE;
    593 
    594 	const char *optspecs = "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrstv:w";
    595 /* Can't actually use getopt(3) because rescanning is not portable */
    596 
    597 rearg:
    598 	inOption = FALSE;
    599 	optscan = NULL;
    600 	while (argc > 1) {
    601 		const char *optspec;
    602 		if (!inOption)
    603 			optscan = argv[1];
    604 		c = *optscan++;
    605 		arginc = 0;
    606 		if (inOption) {
    607 			if (c == '\0') {
    608 				argv++;
    609 				argc--;
    610 				inOption = FALSE;
    611 				continue;
    612 			}
    613 		} else {
    614 			if (c != '-' || dashDash)
    615 				break;
    616 			inOption = TRUE;
    617 			c = *optscan++;
    618 		}
    619 		/* '-' found at some earlier point */
    620 		optspec = strchr(optspecs, c);
    621 		if (c != '\0' && optspec != NULL && optspec[1] == ':') {
    622 			/* -<something> found, and <something> should have an arg */
    623 			inOption = FALSE;
    624 			arginc = 1;
    625 			argvalue = optscan;
    626 			if (*argvalue == '\0') {
    627 				if (argc < 3)
    628 					goto noarg;
    629 				argvalue = argv[2];
    630 				arginc = 2;
    631 			}
    632 		} else {
    633 			argvalue = NULL;
    634 		}
    635 		switch (c) {
    636 		case '\0':
    637 			arginc = 1;
    638 			inOption = FALSE;
    639 			break;
    640 		case '-':
    641 			dashDash = TRUE;
    642 			break;
    643 		default:
    644 			if (!MainParseArg(c, argvalue))
    645 				goto noarg;
    646 		}
    647 		argv += arginc;
    648 		argc -= arginc;
    649 	}
    650 
    651 	/*
    652 	 * See if the rest of the arguments are variable assignments and
    653 	 * perform them if so. Else take them to be targets and stuff them
    654 	 * on the end of the "create" list.
    655 	 */
    656 	for (; argc > 1; ++argv, --argc) {
    657 		VarAssign var;
    658 		if (Parse_IsVar(argv[1], &var)) {
    659 			Parse_DoVar(&var, VAR_CMDLINE);
    660 		} else {
    661 			if (argv[1][0] == '\0')
    662 				Punt("illegal (null) argument.");
    663 			if (argv[1][0] == '-' && !dashDash)
    664 				goto rearg;
    665 			Lst_Append(&opts.create, bmake_strdup(argv[1]));
    666 		}
    667 	}
    668 
    669 	return;
    670 noarg:
    671 	(void)fprintf(stderr, "%s: option requires an argument -- %c\n",
    672 	    progname, c);
    673 	usage();
    674 }
    675 
    676 /*
    677  * Break a line of arguments into words and parse them.
    678  *
    679  * Used when a .MFLAGS or .MAKEFLAGS target is encountered during parsing and
    680  * by main() when reading the MAKEFLAGS environment variable.
    681  */
    682 void
    683 Main_ParseArgLine(const char *line)
    684 {
    685 	Words words;
    686 	char *buf;
    687 
    688 	if (line == NULL)
    689 		return;
    690 	/* XXX: don't use line as an iterator variable */
    691 	for (; *line == ' '; ++line)
    692 		continue;
    693 	if (line[0] == '\0')
    694 		return;
    695 
    696 	{
    697 		FStr argv0 = Var_Value(".MAKE", VAR_GLOBAL);
    698 		buf = str_concat3(argv0.str, " ", line);
    699 		FStr_Done(&argv0);
    700 	}
    701 
    702 	words = Str_Words(buf, TRUE);
    703 	if (words.words == NULL) {
    704 		Error("Unterminated quoted string [%s]", buf);
    705 		free(buf);
    706 		return;
    707 	}
    708 	free(buf);
    709 	MainParseArgs((int)words.len, words.words);
    710 
    711 	Words_Free(words);
    712 }
    713 
    714 Boolean
    715 Main_SetObjdir(Boolean writable, const char *fmt, ...)
    716 {
    717 	struct stat sb;
    718 	char *path;
    719 	char buf[MAXPATHLEN + 1];
    720 	char buf2[MAXPATHLEN + 1];
    721 	Boolean rc = FALSE;
    722 	va_list ap;
    723 
    724 	va_start(ap, fmt);
    725 	vsnprintf(path = buf, MAXPATHLEN, fmt, ap);
    726 	va_end(ap);
    727 
    728 	if (path[0] != '/') {
    729 		snprintf(buf2, MAXPATHLEN, "%s/%s", curdir, path);
    730 		path = buf2;
    731 	}
    732 
    733 	/* look for the directory and try to chdir there */
    734 	if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
    735 		if ((writable && access(path, W_OK) != 0) ||
    736 		    (chdir(path) != 0)) {
    737 			(void)fprintf(stderr, "%s warning: %s: %s.\n",
    738 			    progname, path, strerror(errno));
    739 		} else {
    740 			snprintf(objdir, sizeof objdir, "%s", path);
    741 			Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
    742 			setenv("PWD", objdir, 1);
    743 			Dir_InitDot();
    744 			purge_relative_cached_realpaths();
    745 			rc = TRUE;
    746 			if (opts.enterFlag && strcmp(objdir, curdir) != 0)
    747 				enterFlagObj = TRUE;
    748 		}
    749 	}
    750 
    751 	return rc;
    752 }
    753 
    754 static Boolean
    755 SetVarObjdir(Boolean writable, const char *var, const char *suffix)
    756 {
    757 	FStr path = Var_Value(var, VAR_CMDLINE);
    758 	FStr xpath;
    759 
    760 	if (path.str == NULL || path.str[0] == '\0') {
    761 		FStr_Done(&path);
    762 		return FALSE;
    763 	}
    764 
    765 	/* expand variable substitutions */
    766 	xpath = FStr_InitRefer(path.str);
    767 	if (strchr(path.str, '$') != 0) {
    768 		char *expanded;
    769 		(void)Var_Subst(path.str, VAR_GLOBAL, VARE_WANTRES, &expanded);
    770 		/* TODO: handle errors */
    771 		xpath = FStr_InitOwn(expanded);
    772 	}
    773 
    774 	(void)Main_SetObjdir(writable, "%s%s", xpath.str, suffix);
    775 
    776 	FStr_Done(&xpath);
    777 	FStr_Done(&path);
    778 	return TRUE;
    779 }
    780 
    781 /*
    782  * Splits str into words, adding them to the list.
    783  * The string must be kept alive as long as the list.
    784  */
    785 int
    786 str2Lst_Append(StringList *lp, char *str)
    787 {
    788 	char *cp;
    789 	int n;
    790 
    791 	const char *sep = " \t";
    792 
    793 	for (n = 0, cp = strtok(str, sep); cp; cp = strtok(NULL, sep)) {
    794 		Lst_Append(lp, cp);
    795 		n++;
    796 	}
    797 	return n;
    798 }
    799 
    800 #ifdef SIGINFO
    801 /*ARGSUSED*/
    802 static void
    803 siginfo(int signo MAKE_ATTR_UNUSED)
    804 {
    805 	char dir[MAXPATHLEN];
    806 	char str[2 * MAXPATHLEN];
    807 	int len;
    808 	if (getcwd(dir, sizeof dir) == NULL)
    809 		return;
    810 	len = snprintf(str, sizeof str, "%s: Working in: %s\n", progname, dir);
    811 	if (len > 0)
    812 		(void)write(STDERR_FILENO, str, (size_t)len);
    813 }
    814 #endif
    815 
    816 /* Allow makefiles some control over the mode we run in. */
    817 static void
    818 MakeMode(void)
    819 {
    820 	FStr mode = FStr_InitRefer(NULL);
    821 
    822 	if (mode.str == NULL) {
    823 		char *expanded;
    824 		(void)Var_Subst("${" MAKE_MODE ":tl}",
    825 		    VAR_GLOBAL, VARE_WANTRES, &expanded);
    826 		/* TODO: handle errors */
    827 		mode = FStr_InitOwn(expanded);
    828 	}
    829 
    830 	if (mode.str[0] != '\0') {
    831 		if (strstr(mode.str, "compat") != NULL) {
    832 			opts.compatMake = TRUE;
    833 			forceJobs = FALSE;
    834 		}
    835 #if USE_META
    836 		if (strstr(mode.str, "meta") != NULL)
    837 			meta_mode_init(mode.str);
    838 #endif
    839 	}
    840 
    841 	FStr_Done(&mode);
    842 }
    843 
    844 static void
    845 PrintVar(const char *varname, Boolean expandVars)
    846 {
    847 	if (strchr(varname, '$') != NULL) {
    848 		char *evalue;
    849 		(void)Var_Subst(varname, VAR_GLOBAL, VARE_WANTRES, &evalue);
    850 		/* TODO: handle errors */
    851 		printf("%s\n", evalue);
    852 		bmake_free(evalue);
    853 
    854 	} else if (expandVars) {
    855 		char *expr = str_concat3("${", varname, "}");
    856 		char *evalue;
    857 		(void)Var_Subst(expr, VAR_GLOBAL, VARE_WANTRES, &evalue);
    858 		/* TODO: handle errors */
    859 		free(expr);
    860 		printf("%s\n", evalue);
    861 		bmake_free(evalue);
    862 
    863 	} else {
    864 		FStr value = Var_Value(varname, VAR_GLOBAL);
    865 		printf("%s\n", value.str != NULL ? value.str : "");
    866 		FStr_Done(&value);
    867 	}
    868 }
    869 
    870 /*
    871  * Return a Boolean based on a variable.
    872  *
    873  * If the knob is not set, return the fallback.
    874  * If set, anything that looks or smells like "No", "False", "Off", "0", etc.
    875  * is FALSE, otherwise TRUE.
    876  */
    877 static Boolean
    878 GetBooleanVar(const char *varname, Boolean fallback)
    879 {
    880 	char *expr = str_concat3("${", varname, ":U}");
    881 	char *value;
    882 	Boolean res;
    883 
    884 	(void)Var_Subst(expr, VAR_GLOBAL, VARE_WANTRES, &value);
    885 	/* TODO: handle errors */
    886 	res = ParseBoolean(value, fallback);
    887 	free(value);
    888 	free(expr);
    889 	return res;
    890 }
    891 
    892 static void
    893 doPrintVars(void)
    894 {
    895 	StringListNode *ln;
    896 	Boolean expandVars;
    897 
    898 	if (opts.printVars == PVM_EXPANDED)
    899 		expandVars = TRUE;
    900 	else if (opts.debugVflag)
    901 		expandVars = FALSE;
    902 	else
    903 		expandVars = GetBooleanVar(".MAKE.EXPAND_VARIABLES", FALSE);
    904 
    905 	for (ln = opts.variables.first; ln != NULL; ln = ln->next) {
    906 		const char *varname = ln->datum;
    907 		PrintVar(varname, expandVars);
    908 	}
    909 }
    910 
    911 static Boolean
    912 runTargets(void)
    913 {
    914 	GNodeList targs = LST_INIT;	/* target nodes to create */
    915 	Boolean outOfDate;	/* FALSE if all targets up to date */
    916 
    917 	/*
    918 	 * Have now read the entire graph and need to make a list of
    919 	 * targets to create. If none was given on the command line,
    920 	 * we consult the parsing module to find the main target(s)
    921 	 * to create.
    922 	 */
    923 	if (Lst_IsEmpty(&opts.create))
    924 		Parse_MainName(&targs);
    925 	else
    926 		Targ_FindList(&targs, &opts.create);
    927 
    928 	if (!opts.compatMake) {
    929 		/*
    930 		 * Initialize job module before traversing the graph
    931 		 * now that any .BEGIN and .END targets have been read.
    932 		 * This is done only if the -q flag wasn't given
    933 		 * (to prevent the .BEGIN from being executed should
    934 		 * it exist).
    935 		 */
    936 		if (!opts.queryFlag) {
    937 			Job_Init();
    938 			jobsRunning = TRUE;
    939 		}
    940 
    941 		/* Traverse the graph, checking on all the targets */
    942 		outOfDate = Make_Run(&targs);
    943 	} else {
    944 		/*
    945 		 * Compat_Init will take care of creating all the
    946 		 * targets as well as initializing the module.
    947 		 */
    948 		Compat_Run(&targs);
    949 		outOfDate = FALSE;
    950 	}
    951 	Lst_Done(&targs);	/* Don't free the nodes. */
    952 	return outOfDate;
    953 }
    954 
    955 /*
    956  * Set up the .TARGETS variable to contain the list of targets to be
    957  * created. If none specified, make the variable empty -- the parser
    958  * will fill the thing in with the default or .MAIN target.
    959  */
    960 static void
    961 InitVarTargets(void)
    962 {
    963 	StringListNode *ln;
    964 
    965 	if (Lst_IsEmpty(&opts.create)) {
    966 		Var_Set(".TARGETS", "", VAR_GLOBAL);
    967 		return;
    968 	}
    969 
    970 	for (ln = opts.create.first; ln != NULL; ln = ln->next) {
    971 		char *name = ln->datum;
    972 		Var_Append(".TARGETS", name, VAR_GLOBAL);
    973 	}
    974 }
    975 
    976 static void
    977 InitRandom(void)
    978 {
    979 	struct timeval tv;
    980 
    981 	gettimeofday(&tv, NULL);
    982 	srandom((unsigned int)(tv.tv_sec + tv.tv_usec));
    983 }
    984 
    985 static const char *
    986 InitVarMachine(const struct utsname *utsname)
    987 {
    988 	const char *machine = getenv("MACHINE");
    989 	if (machine != NULL)
    990 		return machine;
    991 
    992 #if defined(MAKE_NATIVE)
    993 	return utsname->machine;
    994 #elif defined(MAKE_MACHINE)
    995 	return MAKE_MACHINE;
    996 #else
    997 	return "unknown";
    998 #endif
    999 }
   1000 
   1001 static const char *
   1002 InitVarMachineArch(void)
   1003 {
   1004 	const char *env = getenv("MACHINE_ARCH");
   1005 	if (env != NULL)
   1006 		return env;
   1007 
   1008 #ifdef MAKE_NATIVE
   1009 	{
   1010 		struct utsname utsname;
   1011 		static char machine_arch_buf[sizeof utsname.machine];
   1012 		const int mib[2] = { CTL_HW, HW_MACHINE_ARCH };
   1013 		size_t len = sizeof machine_arch_buf;
   1014 
   1015 		if (sysctl(mib, __arraycount(mib), machine_arch_buf,
   1016 			&len, NULL, 0) < 0) {
   1017 		    (void)fprintf(stderr, "%s: sysctl failed (%s).\n", progname,
   1018 			strerror(errno));
   1019 		    exit(2);
   1020 		}
   1021 
   1022 		return machine_arch_buf;
   1023 	}
   1024 #elif defined(MACHINE_ARCH)
   1025 	return MACHINE_ARCH;
   1026 #elif defined(MAKE_MACHINE_ARCH)
   1027 	return MAKE_MACHINE_ARCH;
   1028 #else
   1029 	return "unknown";
   1030 #endif
   1031 }
   1032 
   1033 #ifndef NO_PWD_OVERRIDE
   1034 /*
   1035  * All this code is so that we know where we are when we start up
   1036  * on a different machine with pmake.
   1037  *
   1038  * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
   1039  * since the value of curdir can vary depending on how we got
   1040  * here.  Ie sitting at a shell prompt (shell that provides $PWD)
   1041  * or via subdir.mk in which case its likely a shell which does
   1042  * not provide it.
   1043  *
   1044  * So, to stop it breaking this case only, we ignore PWD if
   1045  * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a variable expression.
   1046  */
   1047 static void
   1048 HandlePWD(const struct stat *curdir_st)
   1049 {
   1050 	char *pwd;
   1051 	FStr prefix, makeobjdir;
   1052 	struct stat pwd_st;
   1053 
   1054 	if (ignorePWD || (pwd = getenv("PWD")) == NULL)
   1055 		return;
   1056 
   1057 	prefix = Var_Value("MAKEOBJDIRPREFIX", VAR_CMDLINE);
   1058 	if (prefix.str != NULL) {
   1059 		FStr_Done(&prefix);
   1060 		return;
   1061 	}
   1062 
   1063 	makeobjdir = Var_Value("MAKEOBJDIR", VAR_CMDLINE);
   1064 	if (makeobjdir.str != NULL && strchr(makeobjdir.str, '$') != NULL)
   1065 		goto ignore_pwd;
   1066 
   1067 	if (stat(pwd, &pwd_st) == 0 &&
   1068 	    curdir_st->st_ino == pwd_st.st_ino &&
   1069 	    curdir_st->st_dev == pwd_st.st_dev)
   1070 		(void)strncpy(curdir, pwd, MAXPATHLEN);
   1071 
   1072 ignore_pwd:
   1073 	FStr_Done(&makeobjdir);
   1074 }
   1075 #endif
   1076 
   1077 /*
   1078  * Find the .OBJDIR.  If MAKEOBJDIRPREFIX, or failing that,
   1079  * MAKEOBJDIR is set in the environment, try only that value
   1080  * and fall back to .CURDIR if it does not exist.
   1081  *
   1082  * Otherwise, try _PATH_OBJDIR.MACHINE-MACHINE_ARCH, _PATH_OBJDIR.MACHINE,
   1083  * and * finally _PATH_OBJDIRPREFIX`pwd`, in that order.  If none
   1084  * of these paths exist, just use .CURDIR.
   1085  */
   1086 static void
   1087 InitObjdir(const char *machine, const char *machine_arch)
   1088 {
   1089 	Boolean writable;
   1090 
   1091 	Dir_InitCur(curdir);
   1092 	writable = GetBooleanVar("MAKE_OBJDIR_CHECK_WRITABLE", TRUE);
   1093 	(void)Main_SetObjdir(FALSE, "%s", curdir);
   1094 
   1095 	if (!SetVarObjdir(writable, "MAKEOBJDIRPREFIX", curdir) &&
   1096 	    !SetVarObjdir(writable, "MAKEOBJDIR", "") &&
   1097 	    !Main_SetObjdir(writable, "%s.%s-%s", _PATH_OBJDIR, machine, machine_arch) &&
   1098 	    !Main_SetObjdir(writable, "%s.%s", _PATH_OBJDIR, machine) &&
   1099 	    !Main_SetObjdir(writable, "%s", _PATH_OBJDIR))
   1100 		(void)Main_SetObjdir(writable, "%s%s", _PATH_OBJDIRPREFIX, curdir);
   1101 }
   1102 
   1103 /* get rid of resource limit on file descriptors */
   1104 static void
   1105 UnlimitFiles(void)
   1106 {
   1107 #if defined(MAKE_NATIVE) || (defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE))
   1108 	struct rlimit rl;
   1109 	if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
   1110 	    rl.rlim_cur != rl.rlim_max) {
   1111 		rl.rlim_cur = rl.rlim_max;
   1112 		(void)setrlimit(RLIMIT_NOFILE, &rl);
   1113 	}
   1114 #endif
   1115 }
   1116 
   1117 static void
   1118 CmdOpts_Init(void)
   1119 {
   1120 	opts.compatMake = FALSE;
   1121 	opts.debug = DEBUG_NONE;
   1122 	/* opts.debug_file has been initialized earlier */
   1123 	opts.strict = FALSE;
   1124 	opts.debugVflag = FALSE;
   1125 	opts.checkEnvFirst = FALSE;
   1126 	Lst_Init(&opts.makefiles);
   1127 	opts.ignoreErrors = FALSE;	/* Pay attention to non-zero returns */
   1128 	opts.maxJobs = 1;
   1129 	opts.keepgoing = FALSE;		/* Stop on error */
   1130 	opts.noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
   1131 	opts.noExecute = FALSE;		/* Execute all commands */
   1132 	opts.queryFlag = FALSE;
   1133 	opts.noBuiltins = FALSE;	/* Read the built-in rules */
   1134 	opts.beSilent = FALSE;		/* Print commands as executed */
   1135 	opts.touchFlag = FALSE;
   1136 	opts.printVars = PVM_NONE;
   1137 	Lst_Init(&opts.variables);
   1138 	opts.parseWarnFatal = FALSE;
   1139 	opts.enterFlag = FALSE;
   1140 	opts.varNoExportEnv = FALSE;
   1141 	Lst_Init(&opts.create);
   1142 }
   1143 
   1144 /*
   1145  * Initialize MAKE and .MAKE to the path of the executable, so that it can be
   1146  * found by execvp(3) and the shells, even after a chdir.
   1147  *
   1148  * If it's a relative path and contains a '/', resolve it to an absolute path.
   1149  * Otherwise keep it as is, assuming it will be found in the PATH.
   1150  */
   1151 static void
   1152 InitVarMake(const char *argv0)
   1153 {
   1154 	const char *make = argv0;
   1155 
   1156 	if (argv0[0] != '/' && strchr(argv0, '/') != NULL) {
   1157 		char pathbuf[MAXPATHLEN];
   1158 		const char *abspath = cached_realpath(argv0, pathbuf);
   1159 		struct stat st;
   1160 		if (abspath != NULL && abspath[0] == '/' &&
   1161 		    stat(make, &st) == 0)
   1162 			make = abspath;
   1163 	}
   1164 
   1165 	Var_Set("MAKE", make, VAR_GLOBAL);
   1166 	Var_Set(".MAKE", make, VAR_GLOBAL);
   1167 }
   1168 
   1169 /*
   1170  * Add the directories from the colon-separated syspath to defSysIncPath.
   1171  * After returning, the contents of syspath is unspecified.
   1172  */
   1173 static void
   1174 InitDefSysIncPath(char *syspath)
   1175 {
   1176 	static char defsyspath[] = _PATH_DEFSYSPATH;
   1177 	char *start, *cp;
   1178 
   1179 	/*
   1180 	 * If no user-supplied system path was given (through the -m option)
   1181 	 * add the directories from the DEFSYSPATH (more than one may be given
   1182 	 * as dir1:...:dirn) to the system include path.
   1183 	 */
   1184 	if (syspath == NULL || syspath[0] == '\0')
   1185 		syspath = defsyspath;
   1186 	else
   1187 		syspath = bmake_strdup(syspath);
   1188 
   1189 	for (start = syspath; *start != '\0'; start = cp) {
   1190 		for (cp = start; *cp != '\0' && *cp != ':'; cp++)
   1191 			continue;
   1192 		if (*cp == ':')
   1193 			*cp++ = '\0';
   1194 
   1195 		/* look for magic parent directory search string */
   1196 		if (strncmp(start, ".../", 4) == 0) {
   1197 			char *dir = Dir_FindHereOrAbove(curdir, start + 4);
   1198 			if (dir != NULL) {
   1199 				(void)Dir_AddDir(defSysIncPath, dir);
   1200 				free(dir);
   1201 			}
   1202 		} else {
   1203 			(void)Dir_AddDir(defSysIncPath, start);
   1204 		}
   1205 	}
   1206 
   1207 	if (syspath != defsyspath)
   1208 		free(syspath);
   1209 }
   1210 
   1211 static void
   1212 ReadBuiltinRules(void)
   1213 {
   1214 	StringListNode *ln;
   1215 	StringList sysMkPath = LST_INIT;
   1216 
   1217 	Dir_Expand(_PATH_DEFSYSMK,
   1218 	    Lst_IsEmpty(sysIncPath) ? defSysIncPath : sysIncPath,
   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)Dir_AddDir(&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)
   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)
   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(&buf);
   1843 		res = Buf_Destroy(&buf, FALSE);
   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_GetAll(&buf, NULL), Buf_Len(&buf));
   2028 
   2029 	Buf_Destroy(&buf, TRUE);
   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);
   2097 	}
   2098 	return quietly;
   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 	/* we generally want to keep quiet if a sub-make died */
   2136 	if (shouldDieQuietly(gn, -1))
   2137 		return;
   2138 
   2139 	if (msg != NULL)
   2140 		printf("%s", msg);
   2141 	printf("\n%s: stopped in %s\n", progname, curdir);
   2142 
   2143 	if (errorNode != NULL)
   2144 		return;		/* we've been here! */
   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