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