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