Home | History | Annotate | Line # | Download | only in make
main.c revision 1.240
      1 /*	$NetBSD: main.c,v 1.240 2016/02/18 20:25:08 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.240 2016/02/18 20:25:08 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.240 2016/02/18 20:25:08 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 = 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 	 * Be compatible if user did not specify -j and did not explicitly
   1121 	 * turned compatibility on
   1122 	 */
   1123 	if (!compatMake && !forceJobs) {
   1124 		compatMake = TRUE;
   1125 	}
   1126 
   1127 	/*
   1128 	 * Initialize archive, target and suffix modules in preparation for
   1129 	 * parsing the makefile(s)
   1130 	 */
   1131 	Arch_Init();
   1132 	Targ_Init();
   1133 	Suff_Init();
   1134 	Trace_Init(tracefile);
   1135 
   1136 	DEFAULT = NULL;
   1137 	(void)time(&now);
   1138 
   1139 	Trace_Log(MAKESTART, NULL);
   1140 
   1141 	/*
   1142 	 * Set up the .TARGETS variable to contain the list of targets to be
   1143 	 * created. If none specified, make the variable empty -- the parser
   1144 	 * will fill the thing in with the default or .MAIN target.
   1145 	 */
   1146 	if (!Lst_IsEmpty(create)) {
   1147 		LstNode ln;
   1148 
   1149 		for (ln = Lst_First(create); ln != NULL;
   1150 		    ln = Lst_Succ(ln)) {
   1151 			char *name = (char *)Lst_Datum(ln);
   1152 
   1153 			Var_Append(".TARGETS", name, VAR_GLOBAL);
   1154 		}
   1155 	} else
   1156 		Var_Set(".TARGETS", "", VAR_GLOBAL, 0);
   1157 
   1158 
   1159 	/*
   1160 	 * If no user-supplied system path was given (through the -m option)
   1161 	 * add the directories from the DEFSYSPATH (more than one may be given
   1162 	 * as dir1:...:dirn) to the system include path.
   1163 	 */
   1164 	if (syspath == NULL || *syspath == '\0')
   1165 		syspath = defsyspath;
   1166 	else
   1167 		syspath = bmake_strdup(syspath);
   1168 
   1169 	for (start = syspath; *start != '\0'; start = cp) {
   1170 		for (cp = start; *cp != '\0' && *cp != ':'; cp++)
   1171 			continue;
   1172 		if (*cp == ':') {
   1173 			*cp++ = '\0';
   1174 		}
   1175 		/* look for magic parent directory search string */
   1176 		if (strncmp(".../", start, 4) != 0) {
   1177 			(void)Dir_AddDir(defIncPath, start);
   1178 		} else {
   1179 			if (Dir_FindHereOrAbove(curdir, start+4,
   1180 			    found_path, sizeof(found_path))) {
   1181 				(void)Dir_AddDir(defIncPath, found_path);
   1182 			}
   1183 		}
   1184 	}
   1185 	if (syspath != defsyspath)
   1186 		free(syspath);
   1187 
   1188 	/*
   1189 	 * Read in the built-in rules first, followed by the specified
   1190 	 * makefile, if it was (makefile != NULL), or the default
   1191 	 * makefile and Makefile, in that order, if it wasn't.
   1192 	 */
   1193 	if (!noBuiltins) {
   1194 		LstNode ln;
   1195 
   1196 		sysMkPath = Lst_Init(FALSE);
   1197 		Dir_Expand(_PATH_DEFSYSMK,
   1198 			   Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
   1199 			   sysMkPath);
   1200 		if (Lst_IsEmpty(sysMkPath))
   1201 			Fatal("%s: no system rules (%s).", progname,
   1202 			    _PATH_DEFSYSMK);
   1203 		ln = Lst_Find(sysMkPath, NULL, ReadMakefile);
   1204 		if (ln == NULL)
   1205 			Fatal("%s: cannot open %s.", progname,
   1206 			    (char *)Lst_Datum(ln));
   1207 	}
   1208 
   1209 	if (!Lst_IsEmpty(makefiles)) {
   1210 		LstNode ln;
   1211 
   1212 		ln = Lst_Find(makefiles, NULL, ReadAllMakefiles);
   1213 		if (ln != NULL)
   1214 			Fatal("%s: cannot open %s.", progname,
   1215 			    (char *)Lst_Datum(ln));
   1216 	} else {
   1217 	    p1 = Var_Subst(NULL, "${" MAKEFILE_PREFERENCE "}",
   1218 		VAR_CMD, VARF_WANTRES);
   1219 	    if (p1) {
   1220 		(void)str2Lst_Append(makefiles, p1, NULL);
   1221 		(void)Lst_Find(makefiles, NULL, ReadMakefile);
   1222 		free(p1);
   1223 	    }
   1224 	}
   1225 
   1226 	/* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
   1227 	if (!noBuiltins || !printVars) {
   1228 	    makeDependfile = Var_Subst(NULL, "${.MAKE.DEPENDFILE:T}",
   1229 		VAR_CMD, VARF_WANTRES);
   1230 	    doing_depend = TRUE;
   1231 	    (void)ReadMakefile(makeDependfile, NULL);
   1232 	    doing_depend = FALSE;
   1233 	}
   1234 
   1235 	if (enterFlagObj)
   1236 		printf("%s: Entering directory `%s'\n", progname, objdir);
   1237 
   1238 	MakeMode(NULL);
   1239 
   1240 	Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
   1241 	free(p1);
   1242 
   1243 	if (!compatMake)
   1244 	    Job_ServerStart(maxJobTokens, jp_0, jp_1);
   1245 	if (DEBUG(JOB))
   1246 	    fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
   1247 		jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
   1248 
   1249 	Main_ExportMAKEFLAGS(TRUE);	/* initial export */
   1250 
   1251 
   1252 	/*
   1253 	 * For compatibility, look at the directories in the VPATH variable
   1254 	 * and add them to the search path, if the variable is defined. The
   1255 	 * variable's value is in the same format as the PATH envariable, i.e.
   1256 	 * <directory>:<directory>:<directory>...
   1257 	 */
   1258 	if (Var_Exists("VPATH", VAR_CMD)) {
   1259 		char *vpath, savec;
   1260 		/*
   1261 		 * GCC stores string constants in read-only memory, but
   1262 		 * Var_Subst will want to write this thing, so store it
   1263 		 * in an array
   1264 		 */
   1265 		static char VPATH[] = "${VPATH}";
   1266 
   1267 		vpath = Var_Subst(NULL, VPATH, VAR_CMD, VARF_WANTRES);
   1268 		path = vpath;
   1269 		do {
   1270 			/* skip to end of directory */
   1271 			for (cp = path; *cp != ':' && *cp != '\0'; cp++)
   1272 				continue;
   1273 			/* Save terminator character so know when to stop */
   1274 			savec = *cp;
   1275 			*cp = '\0';
   1276 			/* Add directory to search path */
   1277 			(void)Dir_AddDir(dirSearchPath, path);
   1278 			*cp = savec;
   1279 			path = cp + 1;
   1280 		} while (savec == ':');
   1281 		free(vpath);
   1282 	}
   1283 
   1284 	/*
   1285 	 * Now that all search paths have been read for suffixes et al, it's
   1286 	 * time to add the default search path to their lists...
   1287 	 */
   1288 	Suff_DoPaths();
   1289 
   1290 	/*
   1291 	 * Propagate attributes through :: dependency lists.
   1292 	 */
   1293 	Targ_Propagate();
   1294 
   1295 	/* print the initial graph, if the user requested it */
   1296 	if (DEBUG(GRAPH1))
   1297 		Targ_PrintGraph(1);
   1298 
   1299 	/* print the values of any variables requested by the user */
   1300 	if (printVars) {
   1301 		LstNode ln;
   1302 		Boolean expandVars;
   1303 
   1304 		if (debugVflag)
   1305 			expandVars = FALSE;
   1306 		else
   1307 			expandVars = getBoolean(".MAKE.EXPAND_VARIABLES", FALSE);
   1308 		for (ln = Lst_First(variables); ln != NULL;
   1309 		    ln = Lst_Succ(ln)) {
   1310 			char *var = (char *)Lst_Datum(ln);
   1311 			char *value;
   1312 
   1313 			if (strchr(var, '$')) {
   1314 			    value = p1 = Var_Subst(NULL, var, VAR_GLOBAL,
   1315 						   VARF_WANTRES);
   1316 			} else if (expandVars) {
   1317 				char tmp[128];
   1318 
   1319 				if (snprintf(tmp, sizeof(tmp), "${%s}", var) >= (int)(sizeof(tmp)))
   1320 					Fatal("%s: variable name too big: %s",
   1321 					      progname, var);
   1322 				value = p1 = Var_Subst(NULL, tmp, VAR_GLOBAL,
   1323 						       VARF_WANTRES);
   1324 			} else {
   1325 				value = Var_Value(var, VAR_GLOBAL, &p1);
   1326 			}
   1327 			printf("%s\n", value ? value : "");
   1328 			free(p1);
   1329 		}
   1330 	} else {
   1331 		/*
   1332 		 * Have now read the entire graph and need to make a list of
   1333 		 * targets to create. If none was given on the command line,
   1334 		 * we consult the parsing module to find the main target(s)
   1335 		 * to create.
   1336 		 */
   1337 		if (Lst_IsEmpty(create))
   1338 			targs = Parse_MainName();
   1339 		else
   1340 			targs = Targ_FindList(create, TARG_CREATE);
   1341 
   1342 		if (!compatMake) {
   1343 			/*
   1344 			 * Initialize job module before traversing the graph
   1345 			 * now that any .BEGIN and .END targets have been read.
   1346 			 * This is done only if the -q flag wasn't given
   1347 			 * (to prevent the .BEGIN from being executed should
   1348 			 * it exist).
   1349 			 */
   1350 			if (!queryFlag) {
   1351 				Job_Init();
   1352 				jobsRunning = TRUE;
   1353 			}
   1354 
   1355 			/* Traverse the graph, checking on all the targets */
   1356 			outOfDate = Make_Run(targs);
   1357 		} else {
   1358 			/*
   1359 			 * Compat_Init will take care of creating all the
   1360 			 * targets as well as initializing the module.
   1361 			 */
   1362 			Compat_Run(targs);
   1363 		}
   1364 	}
   1365 
   1366 #ifdef CLEANUP
   1367 	Lst_Destroy(targs, NULL);
   1368 	Lst_Destroy(variables, NULL);
   1369 	Lst_Destroy(makefiles, NULL);
   1370 	Lst_Destroy(create, (FreeProc *)free);
   1371 #endif
   1372 
   1373 	/* print the graph now it's been processed if the user requested it */
   1374 	if (DEBUG(GRAPH2))
   1375 		Targ_PrintGraph(2);
   1376 
   1377 	Trace_Log(MAKEEND, 0);
   1378 
   1379 	if (enterFlagObj)
   1380 		printf("%s: Leaving directory `%s'\n", progname, objdir);
   1381 	if (enterFlag)
   1382 		printf("%s: Leaving directory `%s'\n", progname, curdir);
   1383 
   1384 	Suff_End();
   1385         Targ_End();
   1386 	Arch_End();
   1387 	Var_End();
   1388 	Parse_End();
   1389 	Dir_End();
   1390 	Job_End();
   1391 	Trace_End();
   1392 
   1393 	return outOfDate ? 1 : 0;
   1394 }
   1395 
   1396 /*-
   1397  * ReadMakefile  --
   1398  *	Open and parse the given makefile.
   1399  *
   1400  * Results:
   1401  *	0 if ok. -1 if couldn't open file.
   1402  *
   1403  * Side Effects:
   1404  *	lots
   1405  */
   1406 static int
   1407 ReadMakefile(const void *p, const void *q MAKE_ATTR_UNUSED)
   1408 {
   1409 	const char *fname = p;		/* makefile to read */
   1410 	int fd;
   1411 	size_t len = MAXPATHLEN;
   1412 	char *name, *path = bmake_malloc(len);
   1413 
   1414 	if (!strcmp(fname, "-")) {
   1415 		Parse_File(NULL /*stdin*/, -1);
   1416 		Var_Set("MAKEFILE", "", VAR_INTERNAL, 0);
   1417 	} else {
   1418 		/* if we've chdir'd, rebuild the path name */
   1419 		if (strcmp(curdir, objdir) && *fname != '/') {
   1420 			size_t plen = strlen(curdir) + strlen(fname) + 2;
   1421 			if (len < plen)
   1422 				path = bmake_realloc(path, len = 2 * plen);
   1423 
   1424 			(void)snprintf(path, len, "%s/%s", curdir, fname);
   1425 			fd = open(path, O_RDONLY);
   1426 			if (fd != -1) {
   1427 				fname = path;
   1428 				goto found;
   1429 			}
   1430 
   1431 			/* If curdir failed, try objdir (ala .depend) */
   1432 			plen = strlen(objdir) + strlen(fname) + 2;
   1433 			if (len < plen)
   1434 				path = bmake_realloc(path, len = 2 * plen);
   1435 			(void)snprintf(path, len, "%s/%s", objdir, fname);
   1436 			fd = open(path, O_RDONLY);
   1437 			if (fd != -1) {
   1438 				fname = path;
   1439 				goto found;
   1440 			}
   1441 		} else {
   1442 			fd = open(fname, O_RDONLY);
   1443 			if (fd != -1)
   1444 				goto found;
   1445 		}
   1446 		/* look in -I and system include directories. */
   1447 		name = Dir_FindFile(fname, parseIncPath);
   1448 		if (!name)
   1449 			name = Dir_FindFile(fname,
   1450 				Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
   1451 		if (!name || (fd = open(name, O_RDONLY)) == -1) {
   1452 			free(name);
   1453 			free(path);
   1454 			return(-1);
   1455 		}
   1456 		fname = name;
   1457 		/*
   1458 		 * set the MAKEFILE variable desired by System V fans -- the
   1459 		 * placement of the setting here means it gets set to the last
   1460 		 * makefile specified, as it is set by SysV make.
   1461 		 */
   1462 found:
   1463 		if (!doing_depend)
   1464 			Var_Set("MAKEFILE", fname, VAR_INTERNAL, 0);
   1465 		Parse_File(fname, fd);
   1466 	}
   1467 	free(path);
   1468 	return(0);
   1469 }
   1470 
   1471 
   1472 
   1473 /*-
   1474  * Cmd_Exec --
   1475  *	Execute the command in cmd, and return the output of that command
   1476  *	in a string.
   1477  *
   1478  * Results:
   1479  *	A string containing the output of the command, or the empty string
   1480  *	If errnum is not NULL, it contains the reason for the command failure
   1481  *
   1482  * Side Effects:
   1483  *	The string must be freed by the caller.
   1484  */
   1485 char *
   1486 Cmd_Exec(const char *cmd, const char **errnum)
   1487 {
   1488     const char	*args[4];   	/* Args for invoking the shell */
   1489     int 	fds[2];	    	/* Pipe streams */
   1490     int 	cpid;	    	/* Child PID */
   1491     int 	pid;	    	/* PID from wait() */
   1492     char	*res;		/* result */
   1493     int		status;		/* command exit status */
   1494     Buffer	buf;		/* buffer to store the result */
   1495     char	*cp;
   1496     int		cc;		/* bytes read, or -1 */
   1497     int		savederr;	/* saved errno */
   1498 
   1499 
   1500     *errnum = NULL;
   1501 
   1502     if (!shellName)
   1503 	Shell_Init();
   1504     /*
   1505      * Set up arguments for shell
   1506      */
   1507     args[0] = shellName;
   1508     args[1] = "-c";
   1509     args[2] = cmd;
   1510     args[3] = NULL;
   1511 
   1512     /*
   1513      * Open a pipe for fetching its output
   1514      */
   1515     if (pipe(fds) == -1) {
   1516 	*errnum = "Couldn't create pipe for \"%s\"";
   1517 	goto bad;
   1518     }
   1519 
   1520     /*
   1521      * Fork
   1522      */
   1523     switch (cpid = vFork()) {
   1524     case 0:
   1525 	/*
   1526 	 * Close input side of pipe
   1527 	 */
   1528 	(void)close(fds[0]);
   1529 
   1530 	/*
   1531 	 * Duplicate the output stream to the shell's output, then
   1532 	 * shut the extra thing down. Note we don't fetch the error
   1533 	 * stream...why not? Why?
   1534 	 */
   1535 	(void)dup2(fds[1], 1);
   1536 	(void)close(fds[1]);
   1537 
   1538 	Var_ExportVars();
   1539 
   1540 	(void)execv(shellPath, UNCONST(args));
   1541 	_exit(1);
   1542 	/*NOTREACHED*/
   1543 
   1544     case -1:
   1545 	*errnum = "Couldn't exec \"%s\"";
   1546 	goto bad;
   1547 
   1548     default:
   1549 	/*
   1550 	 * No need for the writing half
   1551 	 */
   1552 	(void)close(fds[1]);
   1553 
   1554 	savederr = 0;
   1555 	Buf_Init(&buf, 0);
   1556 
   1557 	do {
   1558 	    char   result[BUFSIZ];
   1559 	    cc = read(fds[0], result, sizeof(result));
   1560 	    if (cc > 0)
   1561 		Buf_AddBytes(&buf, cc, result);
   1562 	}
   1563 	while (cc > 0 || (cc == -1 && errno == EINTR));
   1564 	if (cc == -1)
   1565 	    savederr = errno;
   1566 
   1567 	/*
   1568 	 * Close the input side of the pipe.
   1569 	 */
   1570 	(void)close(fds[0]);
   1571 
   1572 	/*
   1573 	 * Wait for the process to exit.
   1574 	 */
   1575 	while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) {
   1576 	    JobReapChild(pid, status, FALSE);
   1577 	    continue;
   1578 	}
   1579 	cc = Buf_Size(&buf);
   1580 	res = Buf_Destroy(&buf, FALSE);
   1581 
   1582 	if (savederr != 0)
   1583 	    *errnum = "Couldn't read shell's output for \"%s\"";
   1584 
   1585 	if (WIFSIGNALED(status))
   1586 	    *errnum = "\"%s\" exited on a signal";
   1587 	else if (WEXITSTATUS(status) != 0)
   1588 	    *errnum = "\"%s\" returned non-zero status";
   1589 
   1590 	/*
   1591 	 * Null-terminate the result, convert newlines to spaces and
   1592 	 * install it in the variable.
   1593 	 */
   1594 	res[cc] = '\0';
   1595 	cp = &res[cc];
   1596 
   1597 	if (cc > 0 && *--cp == '\n') {
   1598 	    /*
   1599 	     * A final newline is just stripped
   1600 	     */
   1601 	    *cp-- = '\0';
   1602 	}
   1603 	while (cp >= res) {
   1604 	    if (*cp == '\n') {
   1605 		*cp = ' ';
   1606 	    }
   1607 	    cp--;
   1608 	}
   1609 	break;
   1610     }
   1611     return res;
   1612 bad:
   1613     res = bmake_malloc(1);
   1614     *res = '\0';
   1615     return res;
   1616 }
   1617 
   1618 /*-
   1619  * Error --
   1620  *	Print an error message given its format.
   1621  *
   1622  * Results:
   1623  *	None.
   1624  *
   1625  * Side Effects:
   1626  *	The message is printed.
   1627  */
   1628 /* VARARGS */
   1629 void
   1630 Error(const char *fmt, ...)
   1631 {
   1632 	va_list ap;
   1633 	FILE *err_file;
   1634 
   1635 	err_file = debug_file;
   1636 	if (err_file == stdout)
   1637 		err_file = stderr;
   1638 	(void)fflush(stdout);
   1639 	for (;;) {
   1640 		va_start(ap, fmt);
   1641 		fprintf(err_file, "%s: ", progname);
   1642 		(void)vfprintf(err_file, fmt, ap);
   1643 		va_end(ap);
   1644 		(void)fprintf(err_file, "\n");
   1645 		(void)fflush(err_file);
   1646 		if (err_file == stderr)
   1647 			break;
   1648 		err_file = stderr;
   1649 	}
   1650 }
   1651 
   1652 /*-
   1653  * Fatal --
   1654  *	Produce a Fatal error message. If jobs are running, waits for them
   1655  *	to finish.
   1656  *
   1657  * Results:
   1658  *	None
   1659  *
   1660  * Side Effects:
   1661  *	The program exits
   1662  */
   1663 /* VARARGS */
   1664 void
   1665 Fatal(const char *fmt, ...)
   1666 {
   1667 	va_list ap;
   1668 
   1669 	va_start(ap, fmt);
   1670 	if (jobsRunning)
   1671 		Job_Wait();
   1672 
   1673 	(void)fflush(stdout);
   1674 	(void)vfprintf(stderr, fmt, ap);
   1675 	va_end(ap);
   1676 	(void)fprintf(stderr, "\n");
   1677 	(void)fflush(stderr);
   1678 
   1679 	PrintOnError(NULL, NULL);
   1680 
   1681 	if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
   1682 		Targ_PrintGraph(2);
   1683 	Trace_Log(MAKEERROR, 0);
   1684 	exit(2);		/* Not 1 so -q can distinguish error */
   1685 }
   1686 
   1687 /*
   1688  * Punt --
   1689  *	Major exception once jobs are being created. Kills all jobs, prints
   1690  *	a message and exits.
   1691  *
   1692  * Results:
   1693  *	None
   1694  *
   1695  * Side Effects:
   1696  *	All children are killed indiscriminately and the program Lib_Exits
   1697  */
   1698 /* VARARGS */
   1699 void
   1700 Punt(const char *fmt, ...)
   1701 {
   1702 	va_list ap;
   1703 
   1704 	va_start(ap, fmt);
   1705 	(void)fflush(stdout);
   1706 	(void)fprintf(stderr, "%s: ", progname);
   1707 	(void)vfprintf(stderr, fmt, ap);
   1708 	va_end(ap);
   1709 	(void)fprintf(stderr, "\n");
   1710 	(void)fflush(stderr);
   1711 
   1712 	PrintOnError(NULL, NULL);
   1713 
   1714 	DieHorribly();
   1715 }
   1716 
   1717 /*-
   1718  * DieHorribly --
   1719  *	Exit without giving a message.
   1720  *
   1721  * Results:
   1722  *	None
   1723  *
   1724  * Side Effects:
   1725  *	A big one...
   1726  */
   1727 void
   1728 DieHorribly(void)
   1729 {
   1730 	if (jobsRunning)
   1731 		Job_AbortAll();
   1732 	if (DEBUG(GRAPH2))
   1733 		Targ_PrintGraph(2);
   1734 	Trace_Log(MAKEERROR, 0);
   1735 	exit(2);		/* Not 1, so -q can distinguish error */
   1736 }
   1737 
   1738 /*
   1739  * Finish --
   1740  *	Called when aborting due to errors in child shell to signal
   1741  *	abnormal exit.
   1742  *
   1743  * Results:
   1744  *	None
   1745  *
   1746  * Side Effects:
   1747  *	The program exits
   1748  */
   1749 void
   1750 Finish(int errors)
   1751 	           	/* number of errors encountered in Make_Make */
   1752 {
   1753 	Fatal("%d error%s", errors, errors == 1 ? "" : "s");
   1754 }
   1755 
   1756 /*
   1757  * eunlink --
   1758  *	Remove a file carefully, avoiding directories.
   1759  */
   1760 int
   1761 eunlink(const char *file)
   1762 {
   1763 	struct stat st;
   1764 
   1765 	if (lstat(file, &st) == -1)
   1766 		return -1;
   1767 
   1768 	if (S_ISDIR(st.st_mode)) {
   1769 		errno = EISDIR;
   1770 		return -1;
   1771 	}
   1772 	return unlink(file);
   1773 }
   1774 
   1775 /*
   1776  * execError --
   1777  *	Print why exec failed, avoiding stdio.
   1778  */
   1779 void
   1780 execError(const char *af, const char *av)
   1781 {
   1782 #ifdef USE_IOVEC
   1783 	int i = 0;
   1784 	struct iovec iov[8];
   1785 #define IOADD(s) \
   1786 	(void)(iov[i].iov_base = UNCONST(s), \
   1787 	    iov[i].iov_len = strlen(iov[i].iov_base), \
   1788 	    i++)
   1789 #else
   1790 #define	IOADD(void)write(2, s, strlen(s))
   1791 #endif
   1792 
   1793 	IOADD(progname);
   1794 	IOADD(": ");
   1795 	IOADD(af);
   1796 	IOADD("(");
   1797 	IOADD(av);
   1798 	IOADD(") failed (");
   1799 	IOADD(strerror(errno));
   1800 	IOADD(")\n");
   1801 
   1802 #ifdef USE_IOVEC
   1803 	while (writev(2, iov, 8) == -1 && errno == EAGAIN)
   1804 	    continue;
   1805 #endif
   1806 }
   1807 
   1808 /*
   1809  * usage --
   1810  *	exit with usage message
   1811  */
   1812 static void
   1813 usage(void)
   1814 {
   1815 	char *p;
   1816 	if ((p = strchr(progname, '[')) != NULL)
   1817 	    *p = '\0';
   1818 
   1819 	(void)fprintf(stderr,
   1820 "usage: %s [-BeikNnqrstWwX] \n\
   1821             [-C directory] [-D variable] [-d flags] [-f makefile]\n\
   1822             [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
   1823             [-V variable] [variable=value] [target ...]\n", progname);
   1824 	exit(2);
   1825 }
   1826 
   1827 
   1828 int
   1829 PrintAddr(void *a, void *b)
   1830 {
   1831     printf("%lx ", (unsigned long) a);
   1832     return b ? 0 : 0;
   1833 }
   1834 
   1835 
   1836 
   1837 void
   1838 PrintOnError(GNode *gn, const char *s)
   1839 {
   1840     static GNode *en = NULL;
   1841     char tmp[64];
   1842     char *cp;
   1843 
   1844     if (s)
   1845 	printf("%s", s);
   1846 
   1847     printf("\n%s: stopped in %s\n", progname, curdir);
   1848 
   1849     if (en)
   1850 	return;				/* we've been here! */
   1851     if (gn) {
   1852 	/*
   1853 	 * We can print this even if there is no .ERROR target.
   1854 	 */
   1855 	Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL, 0);
   1856     }
   1857     strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
   1858 	    sizeof(tmp) - 1);
   1859     cp = Var_Subst(NULL, tmp, VAR_GLOBAL, VARF_WANTRES);
   1860     if (cp) {
   1861 	if (*cp)
   1862 	    printf("%s", cp);
   1863 	free(cp);
   1864     }
   1865     fflush(stdout);
   1866 
   1867     /*
   1868      * Finally, see if there is a .ERROR target, and run it if so.
   1869      */
   1870     en = Targ_FindNode(".ERROR", TARG_NOCREATE);
   1871     if (en) {
   1872 	en->type |= OP_SPECIAL;
   1873 	Compat_Make(en, en);
   1874     }
   1875 }
   1876 
   1877 void
   1878 Main_ExportMAKEFLAGS(Boolean first)
   1879 {
   1880     static int once = 1;
   1881     char tmp[64];
   1882     char *s;
   1883 
   1884     if (once != first)
   1885 	return;
   1886     once = 0;
   1887 
   1888     strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
   1889 	    sizeof(tmp));
   1890     s = Var_Subst(NULL, tmp, VAR_CMD, VARF_WANTRES);
   1891     if (s && *s) {
   1892 #ifdef POSIX
   1893 	setenv("MAKEFLAGS", s, 1);
   1894 #else
   1895 	setenv("MAKE", s, 1);
   1896 #endif
   1897     }
   1898 }
   1899 
   1900 char *
   1901 getTmpdir(void)
   1902 {
   1903     static char *tmpdir = NULL;
   1904 
   1905     if (!tmpdir) {
   1906 	struct stat st;
   1907 
   1908 	/*
   1909 	 * Honor $TMPDIR but only if it is valid.
   1910 	 * Ensure it ends with /.
   1911 	 */
   1912 	tmpdir = Var_Subst(NULL, "${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL,
   1913 			   VARF_WANTRES);
   1914 	if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
   1915 	    free(tmpdir);
   1916 	    tmpdir = bmake_strdup(_PATH_TMP);
   1917 	}
   1918     }
   1919     return tmpdir;
   1920 }
   1921 
   1922 /*
   1923  * Create and open a temp file using "pattern".
   1924  * If "fnamep" is provided set it to a copy of the filename created.
   1925  * Otherwise unlink the file once open.
   1926  */
   1927 int
   1928 mkTempFile(const char *pattern, char **fnamep)
   1929 {
   1930     static char *tmpdir = NULL;
   1931     char tfile[MAXPATHLEN];
   1932     int fd;
   1933 
   1934     if (!pattern)
   1935 	pattern = TMPPAT;
   1936     if (!tmpdir)
   1937 	tmpdir = getTmpdir();
   1938     if (pattern[0] == '/') {
   1939 	snprintf(tfile, sizeof(tfile), "%s", pattern);
   1940     } else {
   1941 	snprintf(tfile, sizeof(tfile), "%s%s", tmpdir, pattern);
   1942     }
   1943     if ((fd = mkstemp(tfile)) < 0)
   1944 	Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
   1945     if (fnamep) {
   1946 	*fnamep = bmake_strdup(tfile);
   1947     } else {
   1948 	unlink(tfile);			/* we just want the descriptor */
   1949     }
   1950     return fd;
   1951 }
   1952 
   1953 /*
   1954  * Convert a string representation of a boolean.
   1955  * Anything that looks like "No", "False", "Off", "0" etc,
   1956  * is FALSE, otherwise TRUE.
   1957  */
   1958 Boolean
   1959 s2Boolean(const char *s, Boolean bf)
   1960 {
   1961     if (s) {
   1962 	switch(*s) {
   1963 	case '\0':			/* not set - the default wins */
   1964 	    break;
   1965 	case '0':
   1966 	case 'F':
   1967 	case 'f':
   1968 	case 'N':
   1969 	case 'n':
   1970 	    bf = FALSE;
   1971 	    break;
   1972 	case 'O':
   1973 	case 'o':
   1974 	    switch (s[1]) {
   1975 	    case 'F':
   1976 	    case 'f':
   1977 		bf = FALSE;
   1978 		break;
   1979 	    default:
   1980 		bf = TRUE;
   1981 		break;
   1982 	    }
   1983 	    break;
   1984 	default:
   1985 	    bf = TRUE;
   1986 	    break;
   1987 	}
   1988     }
   1989     return (bf);
   1990 }
   1991 
   1992 /*
   1993  * Return a Boolean based on setting of a knob.
   1994  *
   1995  * If the knob is not set, the supplied default is the return value.
   1996  * If set, anything that looks or smells like "No", "False", "Off", "0" etc,
   1997  * is FALSE, otherwise TRUE.
   1998  */
   1999 Boolean
   2000 getBoolean(const char *name, Boolean bf)
   2001 {
   2002     char tmp[64];
   2003     char *cp;
   2004 
   2005     if (snprintf(tmp, sizeof(tmp), "${%s:tl}", name) < (int)(sizeof(tmp))) {
   2006 	cp = Var_Subst(NULL, tmp, VAR_GLOBAL, VARF_WANTRES);
   2007 
   2008 	if (cp) {
   2009 	    bf = s2Boolean(cp, bf);
   2010 	    free(cp);
   2011 	}
   2012     }
   2013     return (bf);
   2014 }
   2015