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