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