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