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