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