Home | History | Annotate | Line # | Download | only in make
main.c revision 1.229
      1 /*	$NetBSD: main.c,v 1.229 2014/08/23 15:05:40 christos 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.229 2014/08/23 15:05:40 christos 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.229 2014/08/23 15:05:40 christos 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 <fcntl.h>
    129 #include <signal.h>
    130 #include <stdarg.h>
    131 #include <stdio.h>
    132 #include <stdlib.h>
    133 #include <time.h>
    134 #include <ctype.h>
    135 
    136 #include "make.h"
    137 #include "hash.h"
    138 #include "dir.h"
    139 #include "job.h"
    140 #include "pathnames.h"
    141 #include "trace.h"
    142 
    143 #ifdef USE_IOVEC
    144 #include <sys/uio.h>
    145 #endif
    146 
    147 #ifndef	DEFMAXLOCAL
    148 #define	DEFMAXLOCAL DEFMAXJOBS
    149 #endif	/* DEFMAXLOCAL */
    150 
    151 Lst			create;		/* Targets to be made */
    152 time_t			now;		/* Time at start of make */
    153 GNode			*DEFAULT;	/* .DEFAULT node */
    154 Boolean			allPrecious;	/* .PRECIOUS given on line by itself */
    155 
    156 static Boolean		noBuiltins;	/* -r flag */
    157 static Lst		makefiles;	/* ordered list of makefiles to read */
    158 static Boolean		printVars;	/* print value of one or more vars */
    159 static Lst		variables;	/* list of variables to print */
    160 int			maxJobs;	/* -j argument */
    161 static int		maxJobTokens;	/* -j argument */
    162 Boolean			compatMake;	/* -B argument */
    163 int			debug;		/* -d argument */
    164 Boolean			debugVflag;	/* -dV */
    165 Boolean			noExecute;	/* -n flag */
    166 Boolean			noRecursiveExecute;	/* -N flag */
    167 Boolean			keepgoing;	/* -k flag */
    168 Boolean			queryFlag;	/* -q flag */
    169 Boolean			touchFlag;	/* -t flag */
    170 Boolean			enterFlag;	/* -w flag */
    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 static int		MarkSysMkTargets(void *, void *);
    186 
    187 static Boolean		ignorePWD;	/* if we use -C, PWD is meaningless */
    188 static char objdir[MAXPATHLEN + 1];	/* where we chdir'ed to */
    189 char curdir[MAXPATHLEN + 1];		/* Startup directory */
    190 char *progname;				/* the program name */
    191 char *makeDependfile;
    192 pid_t myPid;
    193 int makelevel;
    194 
    195 Boolean forceJobs = FALSE;
    196 
    197 extern Lst parseIncPath;
    198 
    199 /*
    200  * For compatibility with the POSIX version of MAKEFLAGS that includes
    201  * all the options with out -, convert flags to -f -l -a -g -s.
    202  */
    203 static char *
    204 explode(const char *flags)
    205 {
    206     size_t len;
    207     char *nf, *st;
    208     const char *f;
    209 
    210     if (flags == NULL)
    211 	return NULL;
    212 
    213     for (f = flags; *f; f++)
    214 	if (!isalpha((unsigned char)*f))
    215 	    break;
    216 
    217     if (*f)
    218 	return bmake_strdup(flags);
    219 
    220     len = strlen(flags);
    221     st = nf = bmake_malloc(len * 3 + 1);
    222     while (*flags) {
    223 	*nf++ = '-';
    224 	*nf++ = *flags++;
    225 	*nf++ = ' ';
    226     }
    227     *nf = '\0';
    228     return st;
    229 }
    230 
    231 static void
    232 parse_debug_options(const char *argvalue)
    233 {
    234 	const char *modules;
    235 	const char *mode;
    236 	char *fname;
    237 	int len;
    238 
    239 	for (modules = argvalue; *modules; ++modules) {
    240 		switch (*modules) {
    241 		case 'A':
    242 			debug = ~0;
    243 			break;
    244 		case 'a':
    245 			debug |= DEBUG_ARCH;
    246 			break;
    247 		case 'C':
    248 			debug |= DEBUG_CWD;
    249 			break;
    250 		case 'c':
    251 			debug |= DEBUG_COND;
    252 			break;
    253 		case 'd':
    254 			debug |= DEBUG_DIR;
    255 			break;
    256 		case 'e':
    257 			debug |= DEBUG_ERROR;
    258 			break;
    259 		case 'f':
    260 			debug |= DEBUG_FOR;
    261 			break;
    262 		case 'g':
    263 			if (modules[1] == '1') {
    264 				debug |= DEBUG_GRAPH1;
    265 				++modules;
    266 			}
    267 			else if (modules[1] == '2') {
    268 				debug |= DEBUG_GRAPH2;
    269 				++modules;
    270 			}
    271 			else if (modules[1] == '3') {
    272 				debug |= DEBUG_GRAPH3;
    273 				++modules;
    274 			}
    275 			break;
    276 		case 'j':
    277 			debug |= DEBUG_JOB;
    278 			break;
    279 		case 'l':
    280 			debug |= DEBUG_LOUD;
    281 			break;
    282 		case 'M':
    283 			debug |= DEBUG_META;
    284 			break;
    285 		case 'm':
    286 			debug |= DEBUG_MAKE;
    287 			break;
    288 		case 'n':
    289 			debug |= DEBUG_SCRIPT;
    290 			break;
    291 		case 'p':
    292 			debug |= DEBUG_PARSE;
    293 			break;
    294 		case 's':
    295 			debug |= DEBUG_SUFF;
    296 			break;
    297 		case 't':
    298 			debug |= DEBUG_TARG;
    299 			break;
    300 		case 'V':
    301 			debugVflag = TRUE;
    302 			break;
    303 		case 'v':
    304 			debug |= DEBUG_VAR;
    305 			break;
    306 		case 'x':
    307 			debug |= DEBUG_SHELL;
    308 			break;
    309 		case 'F':
    310 			if (debug_file != stdout && debug_file != stderr)
    311 				fclose(debug_file);
    312 			if (*++modules == '+') {
    313 				modules++;
    314 				mode = "a";
    315 			} else
    316 				mode = "w";
    317 			if (strcmp(modules, "stdout") == 0) {
    318 				debug_file = stdout;
    319 				goto debug_setbuf;
    320 			}
    321 			if (strcmp(modules, "stderr") == 0) {
    322 				debug_file = stderr;
    323 				goto debug_setbuf;
    324 			}
    325 			len = strlen(modules);
    326 			fname = malloc(len + 20);
    327 			memcpy(fname, modules, len + 1);
    328 			/* Let the filename be modified by the pid */
    329 			if (strcmp(fname + len - 3, ".%d") == 0)
    330 				snprintf(fname + len - 2, 20, "%d", getpid());
    331 			debug_file = fopen(fname, mode);
    332 			if (!debug_file) {
    333 				fprintf(stderr, "Cannot open debug file %s\n",
    334 				    fname);
    335 				usage();
    336 			}
    337 			free(fname);
    338 			goto debug_setbuf;
    339 		default:
    340 			(void)fprintf(stderr,
    341 			    "%s: illegal argument to d option -- %c\n",
    342 			    progname, *modules);
    343 			usage();
    344 		}
    345 	}
    346 debug_setbuf:
    347 	/*
    348 	 * Make the debug_file unbuffered, and make
    349 	 * stdout line buffered (unless debugfile == stdout).
    350 	 */
    351 	setvbuf(debug_file, NULL, _IONBF, 0);
    352 	if (debug_file != stdout) {
    353 		setvbuf(stdout, NULL, _IOLBF, 0);
    354 	}
    355 }
    356 
    357 /*-
    358  * MainParseArgs --
    359  *	Parse a given argument vector. Called from main() and from
    360  *	Main_ParseArgLine() when the .MAKEFLAGS target is used.
    361  *
    362  *	XXX: Deal with command line overriding .MAKEFLAGS in makefile
    363  *
    364  * Results:
    365  *	None
    366  *
    367  * Side Effects:
    368  *	Various global and local flags will be set depending on the flags
    369  *	given
    370  */
    371 static void
    372 MainParseArgs(int argc, char **argv)
    373 {
    374 	char *p;
    375 	int c = '?';
    376 	int arginc;
    377 	char *argvalue;
    378 	const char *getopt_def;
    379 	char *optscan;
    380 	Boolean inOption, dashDash = FALSE;
    381 	char found_path[MAXPATHLEN + 1];	/* for searching for sys.mk */
    382 
    383 #define OPTFLAGS "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrstw"
    384 /* Can't actually use getopt(3) because rescanning is not portable */
    385 
    386 	getopt_def = OPTFLAGS;
    387 rearg:
    388 	inOption = FALSE;
    389 	optscan = NULL;
    390 	while(argc > 1) {
    391 		char *getopt_spec;
    392 		if(!inOption)
    393 			optscan = argv[1];
    394 		c = *optscan++;
    395 		arginc = 0;
    396 		if(inOption) {
    397 			if(c == '\0') {
    398 				++argv;
    399 				--argc;
    400 				inOption = FALSE;
    401 				continue;
    402 			}
    403 		} else {
    404 			if (c != '-' || dashDash)
    405 				break;
    406 			inOption = TRUE;
    407 			c = *optscan++;
    408 		}
    409 		/* '-' found at some earlier point */
    410 		getopt_spec = strchr(getopt_def, c);
    411 		if(c != '\0' && getopt_spec != NULL && getopt_spec[1] == ':') {
    412 			/* -<something> found, and <something> should have an arg */
    413 			inOption = FALSE;
    414 			arginc = 1;
    415 			argvalue = optscan;
    416 			if(*argvalue == '\0') {
    417 				if (argc < 3)
    418 					goto noarg;
    419 				argvalue = argv[2];
    420 				arginc = 2;
    421 			}
    422 		} else {
    423 			argvalue = NULL;
    424 		}
    425 		switch(c) {
    426 		case '\0':
    427 			arginc = 1;
    428 			inOption = FALSE;
    429 			break;
    430 		case 'B':
    431 			compatMake = TRUE;
    432 			Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
    433 			Var_Set(MAKE_MODE, "compat", VAR_GLOBAL, 0);
    434 			break;
    435 		case 'C':
    436 			if (chdir(argvalue) == -1) {
    437 				(void)fprintf(stderr,
    438 					      "%s: chdir %s: %s\n",
    439 					      progname, argvalue,
    440 					      strerror(errno));
    441 				exit(1);
    442 			}
    443 			if (getcwd(curdir, MAXPATHLEN) == NULL) {
    444 				(void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
    445 				exit(2);
    446 			}
    447 			ignorePWD = TRUE;
    448 			break;
    449 		case 'D':
    450 			if (argvalue == NULL || argvalue[0] == 0) goto noarg;
    451 			Var_Set(argvalue, "1", VAR_GLOBAL, 0);
    452 			Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
    453 			Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    454 			break;
    455 		case 'I':
    456 			if (argvalue == NULL) goto noarg;
    457 			Parse_AddIncludeDir(argvalue);
    458 			Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
    459 			Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    460 			break;
    461 		case 'J':
    462 			if (argvalue == NULL) goto noarg;
    463 			if (sscanf(argvalue, "%d,%d", &jp_0, &jp_1) != 2) {
    464 			    (void)fprintf(stderr,
    465 				"%s: internal error -- J option malformed (%s)\n",
    466 				progname, argvalue);
    467 				usage();
    468 			}
    469 			if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
    470 			    (fcntl(jp_1, F_GETFD, 0) < 0)) {
    471 #if 0
    472 			    (void)fprintf(stderr,
    473 				"%s: ###### warning -- J descriptors were closed!\n",
    474 				progname);
    475 			    exit(2);
    476 #endif
    477 			    jp_0 = -1;
    478 			    jp_1 = -1;
    479 			    compatMake = TRUE;
    480 			} else {
    481 			    Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
    482 			    Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    483 			    jobServer = TRUE;
    484 			}
    485 			break;
    486 		case 'N':
    487 			noExecute = TRUE;
    488 			noRecursiveExecute = TRUE;
    489 			Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
    490 			break;
    491 		case 'S':
    492 			keepgoing = FALSE;
    493 			Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
    494 			break;
    495 		case 'T':
    496 			if (argvalue == NULL) goto noarg;
    497 			tracefile = bmake_strdup(argvalue);
    498 			Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
    499 			Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    500 			break;
    501 		case 'V':
    502 			if (argvalue == NULL) goto noarg;
    503 			printVars = TRUE;
    504 			(void)Lst_AtEnd(variables, argvalue);
    505 			Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
    506 			Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    507 			break;
    508 		case 'W':
    509 			parseWarnFatal = TRUE;
    510 			break;
    511 		case 'X':
    512 			varNoExportEnv = TRUE;
    513 			Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
    514 			break;
    515 		case 'd':
    516 			if (argvalue == NULL) goto noarg;
    517 			/* If '-d-opts' don't pass to children */
    518 			if (argvalue[0] == '-')
    519 			    argvalue++;
    520 			else {
    521 			    Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
    522 			    Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    523 			}
    524 			parse_debug_options(argvalue);
    525 			break;
    526 		case 'e':
    527 			checkEnvFirst = TRUE;
    528 			Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
    529 			break;
    530 		case 'f':
    531 			if (argvalue == NULL) goto noarg;
    532 			(void)Lst_AtEnd(makefiles, argvalue);
    533 			break;
    534 		case 'i':
    535 			ignoreErrors = TRUE;
    536 			Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
    537 			break;
    538 		case 'j':
    539 			if (argvalue == NULL) goto noarg;
    540 			forceJobs = TRUE;
    541 			maxJobs = strtol(argvalue, &p, 0);
    542 			if (*p != '\0' || maxJobs < 1) {
    543 				(void)fprintf(stderr, "%s: illegal argument to -j -- must be positive integer!\n",
    544 				    progname);
    545 				exit(1);
    546 			}
    547 			Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
    548 			Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    549 			Var_Set(".MAKE.JOBS", argvalue, VAR_GLOBAL, 0);
    550 			maxJobTokens = maxJobs;
    551 			break;
    552 		case 'k':
    553 			keepgoing = TRUE;
    554 			Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
    555 			break;
    556 		case 'm':
    557 			if (argvalue == NULL) goto noarg;
    558 			/* look for magic parent directory search string */
    559 			if (strncmp(".../", argvalue, 4) == 0) {
    560 				if (!Dir_FindHereOrAbove(curdir, argvalue+4,
    561 				    found_path, sizeof(found_path)))
    562 					break;		/* nothing doing */
    563 				(void)Dir_AddDir(sysIncPath, found_path);
    564 			} else {
    565 				(void)Dir_AddDir(sysIncPath, argvalue);
    566 			}
    567 			Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
    568 			Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    569 			break;
    570 		case 'n':
    571 			noExecute = TRUE;
    572 			Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
    573 			break;
    574 		case 'q':
    575 			queryFlag = TRUE;
    576 			/* Kind of nonsensical, wot? */
    577 			Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
    578 			break;
    579 		case 'r':
    580 			noBuiltins = TRUE;
    581 			Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
    582 			break;
    583 		case 's':
    584 			beSilent = TRUE;
    585 			Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
    586 			break;
    587 		case 't':
    588 			touchFlag = TRUE;
    589 			Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
    590 			break;
    591 		case 'w':
    592 			enterFlag = TRUE;
    593 			Var_Append(MAKEFLAGS, "-w", VAR_GLOBAL);
    594 			break;
    595 		case '-':
    596 			dashDash = TRUE;
    597 			break;
    598 		default:
    599 		case '?':
    600 			usage();
    601 		}
    602 		argv += arginc;
    603 		argc -= arginc;
    604 	}
    605 
    606 	oldVars = TRUE;
    607 
    608 	/*
    609 	 * See if the rest of the arguments are variable assignments and
    610 	 * perform them if so. Else take them to be targets and stuff them
    611 	 * on the end of the "create" list.
    612 	 */
    613 	for (; argc > 1; ++argv, --argc)
    614 		if (Parse_IsVar(argv[1])) {
    615 			Parse_DoVar(argv[1], VAR_CMD);
    616 		} else {
    617 			if (!*argv[1])
    618 				Punt("illegal (null) argument.");
    619 			if (*argv[1] == '-' && !dashDash)
    620 				goto rearg;
    621 			(void)Lst_AtEnd(create, bmake_strdup(argv[1]));
    622 		}
    623 
    624 	return;
    625 noarg:
    626 	(void)fprintf(stderr, "%s: option requires an argument -- %c\n",
    627 	    progname, c);
    628 	usage();
    629 }
    630 
    631 /*-
    632  * Main_ParseArgLine --
    633  *  	Used by the parse module when a .MFLAGS or .MAKEFLAGS target
    634  *	is encountered and by main() when reading the .MAKEFLAGS envariable.
    635  *	Takes a line of arguments and breaks it into its
    636  * 	component words and passes those words and the number of them to the
    637  *	MainParseArgs function.
    638  *	The line should have all its leading whitespace removed.
    639  *
    640  * Input:
    641  *	line		Line to fracture
    642  *
    643  * Results:
    644  *	None
    645  *
    646  * Side Effects:
    647  *	Only those that come from the various arguments.
    648  */
    649 void
    650 Main_ParseArgLine(const char *line)
    651 {
    652 	char **argv;			/* Manufactured argument vector */
    653 	int argc;			/* Number of arguments in argv */
    654 	char *args;			/* Space used by the args */
    655 	char *buf, *p1;
    656 	char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
    657 	size_t len;
    658 
    659 	if (line == NULL)
    660 		return;
    661 	for (; *line == ' '; ++line)
    662 		continue;
    663 	if (!*line)
    664 		return;
    665 
    666 	buf = bmake_malloc(len = strlen(line) + strlen(argv0) + 2);
    667 	(void)snprintf(buf, len, "%s %s", argv0, line);
    668 	if (p1)
    669 		free(p1);
    670 
    671 	argv = brk_string(buf, &argc, TRUE, &args);
    672 	if (argv == NULL) {
    673 		Error("Unterminated quoted string [%s]", buf);
    674 		free(buf);
    675 		return;
    676 	}
    677 	free(buf);
    678 	MainParseArgs(argc, argv);
    679 
    680 	free(args);
    681 	free(argv);
    682 }
    683 
    684 Boolean
    685 Main_SetObjdir(const char *path)
    686 {
    687 	struct stat sb;
    688 	char *p = NULL;
    689 	char buf[MAXPATHLEN + 1];
    690 	Boolean rc = FALSE;
    691 
    692 	/* expand variable substitutions */
    693 	if (strchr(path, '$') != 0) {
    694 		snprintf(buf, MAXPATHLEN, "%s", path);
    695 		path = p = Var_Subst(NULL, buf, VAR_GLOBAL, 0);
    696 	}
    697 
    698 	if (path[0] != '/') {
    699 		snprintf(buf, MAXPATHLEN, "%s/%s", curdir, path);
    700 		path = buf;
    701 	}
    702 
    703 	/* look for the directory and try to chdir there */
    704 	if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
    705 		if (chdir(path)) {
    706 			(void)fprintf(stderr, "make warning: %s: %s.\n",
    707 				      path, strerror(errno));
    708 		} else {
    709 			strncpy(objdir, path, MAXPATHLEN);
    710 			Var_Set(".OBJDIR", objdir, VAR_GLOBAL, 0);
    711 			setenv("PWD", objdir, 1);
    712 			Dir_InitDot();
    713 			rc = TRUE;
    714 		}
    715 	}
    716 
    717 	if (p)
    718 		free(p);
    719 	return rc;
    720 }
    721 
    722 /*-
    723  * ReadAllMakefiles --
    724  *	wrapper around ReadMakefile() to read all.
    725  *
    726  * Results:
    727  *	TRUE if ok, FALSE on error
    728  */
    729 static int
    730 ReadAllMakefiles(const void *p, const void *q)
    731 {
    732 	return (ReadMakefile(p, q) == 0);
    733 }
    734 
    735 int
    736 str2Lst_Append(Lst lp, char *str, const char *sep)
    737 {
    738     char *cp;
    739     int n;
    740 
    741     if (!sep)
    742 	sep = " \t";
    743 
    744     for (n = 0, cp = strtok(str, sep); cp; cp = strtok(NULL, sep)) {
    745 	(void)Lst_AtEnd(lp, cp);
    746 	n++;
    747     }
    748     return (n);
    749 }
    750 
    751 #ifdef SIGINFO
    752 /*ARGSUSED*/
    753 static void
    754 siginfo(int signo MAKE_ATTR_UNUSED)
    755 {
    756 	char dir[MAXPATHLEN];
    757 	char str[2 * MAXPATHLEN];
    758 	int len;
    759 	if (getcwd(dir, sizeof(dir)) == NULL)
    760 		return;
    761 	len = snprintf(str, sizeof(str), "%s: Working in: %s\n", progname, dir);
    762 	if (len > 0)
    763 		(void)write(STDERR_FILENO, str, (size_t)len);
    764 }
    765 #endif
    766 
    767 /*
    768  * Allow makefiles some control over the mode we run in.
    769  */
    770 void
    771 MakeMode(const char *mode)
    772 {
    773     char *mp = NULL;
    774 
    775     if (!mode)
    776 	mode = mp = Var_Subst(NULL, "${" MAKE_MODE ":tl}", VAR_GLOBAL, 0);
    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     if (mp)
    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 	 * Rules from system makefiles are somewhat special.  For instance,
   1210 	 * they're not eligible to become main targets.  A sensible sys.mk
   1211 	 * only contains suffix transformations and variables, but clearing
   1212 	 * the suffix list makes suffix transformations into regular rules,
   1213 	 * which could otherwise become main targets.
   1214 	 */
   1215 	Lst_ForEach(Targ_List(), MarkSysMkTargets, NULL);
   1216 
   1217 	if (!Lst_IsEmpty(makefiles)) {
   1218 		LstNode ln;
   1219 
   1220 		ln = Lst_Find(makefiles, NULL, ReadAllMakefiles);
   1221 		if (ln != NULL)
   1222 			Fatal("%s: cannot open %s.", progname,
   1223 			    (char *)Lst_Datum(ln));
   1224 	} else {
   1225 	    p1 = Var_Subst(NULL, "${" MAKEFILE_PREFERENCE "}",
   1226 		VAR_CMD, 0);
   1227 	    if (p1) {
   1228 		(void)str2Lst_Append(makefiles, p1, NULL);
   1229 		(void)Lst_Find(makefiles, NULL, ReadMakefile);
   1230 		free(p1);
   1231 	    }
   1232 	}
   1233 
   1234 	/* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
   1235 	if (!noBuiltins || !printVars) {
   1236 	    makeDependfile = Var_Subst(NULL, "${.MAKE.DEPENDFILE:T}",
   1237 		VAR_CMD, 0);
   1238 	    doing_depend = TRUE;
   1239 	    (void)ReadMakefile(makeDependfile, NULL);
   1240 	    doing_depend = FALSE;
   1241 	}
   1242 
   1243 	MakeMode(NULL);
   1244 
   1245 	Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
   1246 	if (p1)
   1247 	    free(p1);
   1248 
   1249 	if (!compatMake)
   1250 	    Job_ServerStart(maxJobTokens, jp_0, jp_1);
   1251 	if (DEBUG(JOB))
   1252 	    fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
   1253 		jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
   1254 
   1255 	Main_ExportMAKEFLAGS(TRUE);	/* initial export */
   1256 
   1257 
   1258 	/*
   1259 	 * For compatibility, look at the directories in the VPATH variable
   1260 	 * and add them to the search path, if the variable is defined. The
   1261 	 * variable's value is in the same format as the PATH envariable, i.e.
   1262 	 * <directory>:<directory>:<directory>...
   1263 	 */
   1264 	if (Var_Exists("VPATH", VAR_CMD)) {
   1265 		char *vpath, savec;
   1266 		/*
   1267 		 * GCC stores string constants in read-only memory, but
   1268 		 * Var_Subst will want to write this thing, so store it
   1269 		 * in an array
   1270 		 */
   1271 		static char VPATH[] = "${VPATH}";
   1272 
   1273 		vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
   1274 		path = vpath;
   1275 		do {
   1276 			/* skip to end of directory */
   1277 			for (cp = path; *cp != ':' && *cp != '\0'; cp++)
   1278 				continue;
   1279 			/* Save terminator character so know when to stop */
   1280 			savec = *cp;
   1281 			*cp = '\0';
   1282 			/* Add directory to search path */
   1283 			(void)Dir_AddDir(dirSearchPath, path);
   1284 			*cp = savec;
   1285 			path = cp + 1;
   1286 		} while (savec == ':');
   1287 		free(vpath);
   1288 	}
   1289 
   1290 	/*
   1291 	 * Now that all search paths have been read for suffixes et al, it's
   1292 	 * time to add the default search path to their lists...
   1293 	 */
   1294 	Suff_DoPaths();
   1295 
   1296 	/*
   1297 	 * Propagate attributes through :: dependency lists.
   1298 	 */
   1299 	Targ_Propagate();
   1300 
   1301 	/* print the initial graph, if the user requested it */
   1302 	if (DEBUG(GRAPH1))
   1303 		Targ_PrintGraph(1);
   1304 
   1305 	/* print the values of any variables requested by the user */
   1306 	if (printVars) {
   1307 		LstNode ln;
   1308 		Boolean expandVars;
   1309 
   1310 		if (debugVflag)
   1311 			expandVars = FALSE;
   1312 		else
   1313 			expandVars = getBoolean(".MAKE.EXPAND_VARIABLES", FALSE);
   1314 		for (ln = Lst_First(variables); ln != NULL;
   1315 		    ln = Lst_Succ(ln)) {
   1316 			char *var = (char *)Lst_Datum(ln);
   1317 			char *value;
   1318 
   1319 			if (strchr(var, '$')) {
   1320 				value = p1 = Var_Subst(NULL, var, VAR_GLOBAL, 0);
   1321 			} else if (expandVars) {
   1322 				char tmp[128];
   1323 
   1324 				if (snprintf(tmp, sizeof(tmp), "${%s}", var) >= (int)(sizeof(tmp)))
   1325 					Fatal("%s: variable name too big: %s",
   1326 					      progname, var);
   1327 				value = p1 = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
   1328 			} else {
   1329 				value = Var_Value(var, VAR_GLOBAL, &p1);
   1330 			}
   1331 			printf("%s\n", value ? value : "");
   1332 			if (p1)
   1333 				free(p1);
   1334 		}
   1335 	} else {
   1336 		/*
   1337 		 * Have now read the entire graph and need to make a list of
   1338 		 * targets to create. If none was given on the command line,
   1339 		 * we consult the parsing module to find the main target(s)
   1340 		 * to create.
   1341 		 */
   1342 		if (Lst_IsEmpty(create))
   1343 			targs = Parse_MainName();
   1344 		else
   1345 			targs = Targ_FindList(create, TARG_CREATE);
   1346 
   1347 		if (!compatMake) {
   1348 			/*
   1349 			 * Initialize job module before traversing the graph
   1350 			 * now that any .BEGIN and .END targets have been read.
   1351 			 * This is done only if the -q flag wasn't given
   1352 			 * (to prevent the .BEGIN from being executed should
   1353 			 * it exist).
   1354 			 */
   1355 			if (!queryFlag) {
   1356 				Job_Init();
   1357 				jobsRunning = TRUE;
   1358 			}
   1359 
   1360 			/* Traverse the graph, checking on all the targets */
   1361 			outOfDate = Make_Run(targs);
   1362 		} else {
   1363 			/*
   1364 			 * Compat_Init will take care of creating all the
   1365 			 * targets as well as initializing the module.
   1366 			 */
   1367 			Compat_Run(targs);
   1368 		}
   1369 	}
   1370 
   1371 #ifdef CLEANUP
   1372 	Lst_Destroy(targs, NULL);
   1373 	Lst_Destroy(variables, NULL);
   1374 	Lst_Destroy(makefiles, NULL);
   1375 	Lst_Destroy(create, (FreeProc *)free);
   1376 #endif
   1377 
   1378 	/* print the graph now it's been processed if the user requested it */
   1379 	if (DEBUG(GRAPH2))
   1380 		Targ_PrintGraph(2);
   1381 
   1382 	Trace_Log(MAKEEND, 0);
   1383 
   1384 	if (enterFlag)
   1385 		printf("%s: Leaving directory `%s'\n", progname, curdir);
   1386 
   1387         Targ_End();
   1388 	Suff_End(); /* targets refer to suffixes, clean after Targ */
   1389 	Arch_End();
   1390 	Var_End();
   1391 	Parse_End();
   1392 	Dir_End();
   1393 	Job_End();
   1394 	Trace_End();
   1395 
   1396 	return outOfDate ? 1 : 0;
   1397 }
   1398 
   1399 /*-
   1400  * ReadMakefile  --
   1401  *	Open and parse the given makefile.
   1402  *
   1403  * Results:
   1404  *	0 if ok. -1 if couldn't open file.
   1405  *
   1406  * Side Effects:
   1407  *	lots
   1408  */
   1409 static int
   1410 ReadMakefile(const void *p, const void *q MAKE_ATTR_UNUSED)
   1411 {
   1412 	const char *fname = p;		/* makefile to read */
   1413 	int fd;
   1414 	size_t len = MAXPATHLEN;
   1415 	char *name, *path = bmake_malloc(len);
   1416 
   1417 	if (!strcmp(fname, "-")) {
   1418 		Parse_File(NULL /*stdin*/, -1);
   1419 		Var_Set("MAKEFILE", "", VAR_INTERNAL, 0);
   1420 	} else {
   1421 		/* if we've chdir'd, rebuild the path name */
   1422 		if (strcmp(curdir, objdir) && *fname != '/') {
   1423 			size_t plen = strlen(curdir) + strlen(fname) + 2;
   1424 			if (len < plen)
   1425 				path = bmake_realloc(path, len = 2 * plen);
   1426 
   1427 			(void)snprintf(path, len, "%s/%s", curdir, fname);
   1428 			fd = open(path, O_RDONLY);
   1429 			if (fd != -1) {
   1430 				fname = path;
   1431 				goto found;
   1432 			}
   1433 
   1434 			/* If curdir failed, try objdir (ala .depend) */
   1435 			plen = strlen(objdir) + strlen(fname) + 2;
   1436 			if (len < plen)
   1437 				path = bmake_realloc(path, len = 2 * plen);
   1438 			(void)snprintf(path, len, "%s/%s", objdir, fname);
   1439 			fd = open(path, O_RDONLY);
   1440 			if (fd != -1) {
   1441 				fname = path;
   1442 				goto found;
   1443 			}
   1444 		} else {
   1445 			fd = open(fname, O_RDONLY);
   1446 			if (fd != -1)
   1447 				goto found;
   1448 		}
   1449 		/* look in -I and system include directories. */
   1450 		name = Dir_FindFile(fname, parseIncPath);
   1451 		if (!name)
   1452 			name = Dir_FindFile(fname,
   1453 				Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
   1454 		if (!name || (fd = open(name, O_RDONLY)) == -1) {
   1455 			if (name)
   1456 				free(name);
   1457 			free(path);
   1458 			return(-1);
   1459 		}
   1460 		fname = name;
   1461 		/*
   1462 		 * set the MAKEFILE variable desired by System V fans -- the
   1463 		 * placement of the setting here means it gets set to the last
   1464 		 * makefile specified, as it is set by SysV make.
   1465 		 */
   1466 found:
   1467 		if (!doing_depend)
   1468 			Var_Set("MAKEFILE", fname, VAR_INTERNAL, 0);
   1469 		Parse_File(fname, fd);
   1470 	}
   1471 	free(path);
   1472 	return(0);
   1473 }
   1474 
   1475 
   1476 
   1477 /*-
   1478  * Cmd_Exec --
   1479  *	Execute the command in cmd, and return the output of that command
   1480  *	in a string.
   1481  *
   1482  * Results:
   1483  *	A string containing the output of the command, or the empty string
   1484  *	If errnum is not NULL, it contains the reason for the command failure
   1485  *
   1486  * Side Effects:
   1487  *	The string must be freed by the caller.
   1488  */
   1489 char *
   1490 Cmd_Exec(const char *cmd, const char **errnum)
   1491 {
   1492     const char	*args[4];   	/* Args for invoking the shell */
   1493     int 	fds[2];	    	/* Pipe streams */
   1494     int 	cpid;	    	/* Child PID */
   1495     int 	pid;	    	/* PID from wait() */
   1496     char	*res;		/* result */
   1497     int		status;		/* command exit status */
   1498     Buffer	buf;		/* buffer to store the result */
   1499     char	*cp;
   1500     int		cc;		/* bytes read, or -1 */
   1501     int		savederr;	/* saved errno */
   1502 
   1503 
   1504     *errnum = NULL;
   1505     savederr = 0;
   1506 
   1507     if (!shellName)
   1508 	Shell_Init();
   1509     /*
   1510      * Set up arguments for shell
   1511      */
   1512     args[0] = shellName;
   1513     args[1] = "-c";
   1514     args[2] = cmd;
   1515     args[3] = NULL;
   1516 
   1517     /*
   1518      * Open a pipe for fetching its output
   1519      */
   1520     if (pipe(fds) == -1) {
   1521 	*errnum = "Couldn't create pipe for \"%s\"";
   1522 	goto bad;
   1523     }
   1524 
   1525     /*
   1526      * Fork
   1527      */
   1528     switch (cpid = vFork()) {
   1529     case 0:
   1530 	/*
   1531 	 * Close input side of pipe
   1532 	 */
   1533 	(void)close(fds[0]);
   1534 
   1535 	/*
   1536 	 * Duplicate the output stream to the shell's output, then
   1537 	 * shut the extra thing down. Note we don't fetch the error
   1538 	 * stream...why not? Why?
   1539 	 */
   1540 	(void)dup2(fds[1], 1);
   1541 	(void)close(fds[1]);
   1542 
   1543 	Var_ExportVars();
   1544 
   1545 	(void)execv(shellPath, UNCONST(args));
   1546 	_exit(1);
   1547 	/*NOTREACHED*/
   1548 
   1549     case -1:
   1550 	*errnum = "Couldn't exec \"%s\"";
   1551 	goto bad;
   1552 
   1553     default:
   1554 	/*
   1555 	 * No need for the writing half
   1556 	 */
   1557 	(void)close(fds[1]);
   1558 
   1559 	Buf_Init(&buf, 0);
   1560 
   1561 	do {
   1562 	    char   result[BUFSIZ];
   1563 	    cc = read(fds[0], result, sizeof(result));
   1564 	    if (cc > 0)
   1565 		Buf_AddBytes(&buf, cc, result);
   1566 	}
   1567 	while (cc > 0 || (cc == -1 && errno == EINTR));
   1568 	if (cc == -1)
   1569 	    savederr = errno;
   1570 
   1571 	/*
   1572 	 * Close the input side of the pipe.
   1573 	 */
   1574 	(void)close(fds[0]);
   1575 
   1576 	/*
   1577 	 * Wait for the process to exit.
   1578 	 */
   1579 	while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) {
   1580 	    JobReapChild(pid, status, FALSE);
   1581 	    continue;
   1582 	}
   1583 	cc = Buf_Size(&buf);
   1584 	res = Buf_Destroy(&buf, FALSE);
   1585 
   1586 	if (savederr != 0)
   1587 	    *errnum = "Couldn't read shell's output for \"%s\"";
   1588 
   1589 	if (WIFSIGNALED(status))
   1590 	    *errnum = "\"%s\" exited on a signal";
   1591 	else if (WEXITSTATUS(status) != 0)
   1592 	    *errnum = "\"%s\" returned non-zero status";
   1593 
   1594 	/*
   1595 	 * Null-terminate the result, convert newlines to spaces and
   1596 	 * install it in the variable.
   1597 	 */
   1598 	res[cc] = '\0';
   1599 	cp = &res[cc];
   1600 
   1601 	if (cc > 0 && *--cp == '\n') {
   1602 	    /*
   1603 	     * A final newline is just stripped
   1604 	     */
   1605 	    *cp-- = '\0';
   1606 	}
   1607 	while (cp >= res) {
   1608 	    if (*cp == '\n') {
   1609 		*cp = ' ';
   1610 	    }
   1611 	    cp--;
   1612 	}
   1613 	break;
   1614     }
   1615     return res;
   1616 bad:
   1617     res = bmake_malloc(1);
   1618     *res = '\0';
   1619     return res;
   1620 }
   1621 
   1622 /*-
   1623  * Error --
   1624  *	Print an error message given its format.
   1625  *
   1626  * Results:
   1627  *	None.
   1628  *
   1629  * Side Effects:
   1630  *	The message is printed.
   1631  */
   1632 /* VARARGS */
   1633 void
   1634 Error(const char *fmt, ...)
   1635 {
   1636 	va_list ap;
   1637 	FILE *err_file;
   1638 
   1639 	err_file = debug_file;
   1640 	if (err_file == stdout)
   1641 		err_file = stderr;
   1642 	(void)fflush(stdout);
   1643 	for (;;) {
   1644 		va_start(ap, fmt);
   1645 		fprintf(err_file, "%s: ", progname);
   1646 		(void)vfprintf(err_file, fmt, ap);
   1647 		va_end(ap);
   1648 		(void)fprintf(err_file, "\n");
   1649 		(void)fflush(err_file);
   1650 		if (err_file == stderr)
   1651 			break;
   1652 		err_file = stderr;
   1653 	}
   1654 }
   1655 
   1656 /*-
   1657  * Fatal --
   1658  *	Produce a Fatal error message. If jobs are running, waits for them
   1659  *	to finish.
   1660  *
   1661  * Results:
   1662  *	None
   1663  *
   1664  * Side Effects:
   1665  *	The program exits
   1666  */
   1667 /* VARARGS */
   1668 void
   1669 Fatal(const char *fmt, ...)
   1670 {
   1671 	va_list ap;
   1672 
   1673 	va_start(ap, fmt);
   1674 	if (jobsRunning)
   1675 		Job_Wait();
   1676 
   1677 	(void)fflush(stdout);
   1678 	(void)vfprintf(stderr, fmt, ap);
   1679 	va_end(ap);
   1680 	(void)fprintf(stderr, "\n");
   1681 	(void)fflush(stderr);
   1682 
   1683 	PrintOnError(NULL, NULL);
   1684 
   1685 	if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
   1686 		Targ_PrintGraph(2);
   1687 	Trace_Log(MAKEERROR, 0);
   1688 	exit(2);		/* Not 1 so -q can distinguish error */
   1689 }
   1690 
   1691 /*
   1692  * Punt --
   1693  *	Major exception once jobs are being created. Kills all jobs, prints
   1694  *	a message and exits.
   1695  *
   1696  * Results:
   1697  *	None
   1698  *
   1699  * Side Effects:
   1700  *	All children are killed indiscriminately and the program Lib_Exits
   1701  */
   1702 /* VARARGS */
   1703 void
   1704 Punt(const char *fmt, ...)
   1705 {
   1706 	va_list ap;
   1707 
   1708 	va_start(ap, fmt);
   1709 	(void)fflush(stdout);
   1710 	(void)fprintf(stderr, "%s: ", progname);
   1711 	(void)vfprintf(stderr, fmt, ap);
   1712 	va_end(ap);
   1713 	(void)fprintf(stderr, "\n");
   1714 	(void)fflush(stderr);
   1715 
   1716 	PrintOnError(NULL, NULL);
   1717 
   1718 	DieHorribly();
   1719 }
   1720 
   1721 /*-
   1722  * DieHorribly --
   1723  *	Exit without giving a message.
   1724  *
   1725  * Results:
   1726  *	None
   1727  *
   1728  * Side Effects:
   1729  *	A big one...
   1730  */
   1731 void
   1732 DieHorribly(void)
   1733 {
   1734 	if (jobsRunning)
   1735 		Job_AbortAll();
   1736 	if (DEBUG(GRAPH2))
   1737 		Targ_PrintGraph(2);
   1738 	Trace_Log(MAKEERROR, 0);
   1739 	exit(2);		/* Not 1, so -q can distinguish error */
   1740 }
   1741 
   1742 /*
   1743  * Finish --
   1744  *	Called when aborting due to errors in child shell to signal
   1745  *	abnormal exit.
   1746  *
   1747  * Results:
   1748  *	None
   1749  *
   1750  * Side Effects:
   1751  *	The program exits
   1752  */
   1753 void
   1754 Finish(int errors)
   1755 	           	/* number of errors encountered in Make_Make */
   1756 {
   1757 	Fatal("%d error%s", errors, errors == 1 ? "" : "s");
   1758 }
   1759 
   1760 /*
   1761  * eunlink --
   1762  *	Remove a file carefully, avoiding directories.
   1763  */
   1764 int
   1765 eunlink(const char *file)
   1766 {
   1767 	struct stat st;
   1768 
   1769 	if (lstat(file, &st) == -1)
   1770 		return -1;
   1771 
   1772 	if (S_ISDIR(st.st_mode)) {
   1773 		errno = EISDIR;
   1774 		return -1;
   1775 	}
   1776 	return unlink(file);
   1777 }
   1778 
   1779 /*
   1780  * execError --
   1781  *	Print why exec failed, avoiding stdio.
   1782  */
   1783 void
   1784 execError(const char *af, const char *av)
   1785 {
   1786 #ifdef USE_IOVEC
   1787 	int i = 0;
   1788 	struct iovec iov[8];
   1789 #define IOADD(s) \
   1790 	(void)(iov[i].iov_base = UNCONST(s), \
   1791 	    iov[i].iov_len = strlen(iov[i].iov_base), \
   1792 	    i++)
   1793 #else
   1794 #define	IOADD(void)write(2, s, strlen(s))
   1795 #endif
   1796 
   1797 	IOADD(progname);
   1798 	IOADD(": ");
   1799 	IOADD(af);
   1800 	IOADD("(");
   1801 	IOADD(av);
   1802 	IOADD(") failed (");
   1803 	IOADD(strerror(errno));
   1804 	IOADD(")\n");
   1805 
   1806 #ifdef USE_IOVEC
   1807 	while (writev(2, iov, 8) == -1 && errno == EAGAIN)
   1808 	    continue;
   1809 #endif
   1810 }
   1811 
   1812 /*
   1813  * usage --
   1814  *	exit with usage message
   1815  */
   1816 static void
   1817 usage(void)
   1818 {
   1819 	char *p;
   1820 	if ((p = strchr(progname, '[')) != NULL)
   1821 	    *p = '\0';
   1822 
   1823 	(void)fprintf(stderr,
   1824 "usage: %s [-BeikNnqrstWwX] \n\
   1825             [-C directory] [-D variable] [-d flags] [-f makefile]\n\
   1826             [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
   1827             [-V variable] [variable=value] [target ...]\n", progname);
   1828 	exit(2);
   1829 }
   1830 
   1831 /*-
   1832  *-----------------------------------------------------------------------
   1833  * MarkSysMkTargets -- set OP_FROM_SYS_MK on a target node in Lst_ForEach().
   1834  *
   1835  * Input:
   1836  *	target	node to set the attribute on (GNode *)
   1837  *
   1838  * Results:
   1839  *	Always 0 to not abort Lst_ForEach() prematurely.
   1840  *-----------------------------------------------------------------------
   1841  */
   1842 static int
   1843 MarkSysMkTargets(void *target, void *unused)
   1844 {
   1845     (void)unused;
   1846     ((GNode *)target)->type |= OP_FROM_SYS_MK;
   1847     return 0;
   1848 }
   1849 
   1850 
   1851 int
   1852 PrintAddr(void *a, void *b)
   1853 {
   1854     printf("%lx ", (unsigned long) a);
   1855     return b ? 0 : 0;
   1856 }
   1857 
   1858 
   1859 
   1860 void
   1861 PrintOnError(GNode *gn, const char *s)
   1862 {
   1863     static GNode *en = NULL;
   1864     char tmp[64];
   1865     char *cp;
   1866 
   1867     if (s)
   1868 	printf("%s", s);
   1869 
   1870     printf("\n%s: stopped in %s\n", progname, curdir);
   1871 
   1872     if (en)
   1873 	return;				/* we've been here! */
   1874     if (gn) {
   1875 	/*
   1876 	 * We can print this even if there is no .ERROR target.
   1877 	 */
   1878 	Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL, 0);
   1879     }
   1880     strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
   1881 	    sizeof(tmp) - 1);
   1882     cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
   1883     if (cp) {
   1884 	if (*cp)
   1885 	    printf("%s", cp);
   1886 	free(cp);
   1887     }
   1888     /*
   1889      * Finally, see if there is a .ERROR target, and run it if so.
   1890      */
   1891     en = Targ_FindNode(".ERROR", TARG_NOCREATE);
   1892     if (en) {
   1893 	en->type |= OP_SPECIAL;
   1894 	Compat_Make(en, en);
   1895     }
   1896 }
   1897 
   1898 void
   1899 Main_ExportMAKEFLAGS(Boolean first)
   1900 {
   1901     static int once = 1;
   1902     char tmp[64];
   1903     char *s;
   1904 
   1905     if (once != first)
   1906 	return;
   1907     once = 0;
   1908 
   1909     strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
   1910 	    sizeof(tmp));
   1911     s = Var_Subst(NULL, tmp, VAR_CMD, 0);
   1912     if (s && *s) {
   1913 #ifdef POSIX
   1914 	setenv("MAKEFLAGS", s, 1);
   1915 #else
   1916 	setenv("MAKE", s, 1);
   1917 #endif
   1918     }
   1919 }
   1920 
   1921 char *
   1922 getTmpdir(void)
   1923 {
   1924     static char *tmpdir = NULL;
   1925 
   1926     if (!tmpdir) {
   1927 	struct stat st;
   1928 
   1929 	/*
   1930 	 * Honor $TMPDIR but only if it is valid.
   1931 	 * Ensure it ends with /.
   1932 	 */
   1933 	tmpdir = Var_Subst(NULL, "${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL, 0);
   1934 	if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
   1935 	    free(tmpdir);
   1936 	    tmpdir = bmake_strdup(_PATH_TMP);
   1937 	}
   1938     }
   1939     return tmpdir;
   1940 }
   1941 
   1942 /*
   1943  * Create and open a temp file using "pattern".
   1944  * If "fnamep" is provided set it to a copy of the filename created.
   1945  * Otherwise unlink the file once open.
   1946  */
   1947 int
   1948 mkTempFile(const char *pattern, char **fnamep)
   1949 {
   1950     static char *tmpdir = NULL;
   1951     char tfile[MAXPATHLEN];
   1952     int fd;
   1953 
   1954     if (!pattern)
   1955 	pattern = TMPPAT;
   1956     if (!tmpdir)
   1957 	tmpdir = getTmpdir();
   1958     if (pattern[0] == '/') {
   1959 	snprintf(tfile, sizeof(tfile), "%s", pattern);
   1960     } else {
   1961 	snprintf(tfile, sizeof(tfile), "%s%s", tmpdir, pattern);
   1962     }
   1963     if ((fd = mkstemp(tfile)) < 0)
   1964 	Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
   1965     if (fnamep) {
   1966 	*fnamep = bmake_strdup(tfile);
   1967     } else {
   1968 	unlink(tfile);			/* we just want the descriptor */
   1969     }
   1970     return fd;
   1971 }
   1972 
   1973 
   1974 /*
   1975  * Return a Boolean based on setting of a knob.
   1976  *
   1977  * If the knob is not set, the supplied default is the return value.
   1978  * If set, anything that looks or smells like "No", "False", "Off", "0" etc,
   1979  * is FALSE, otherwise TRUE.
   1980  */
   1981 Boolean
   1982 getBoolean(const char *name, Boolean bf)
   1983 {
   1984     char tmp[64];
   1985     char *cp;
   1986 
   1987     if (snprintf(tmp, sizeof(tmp), "${%s:tl}", name) < (int)(sizeof(tmp))) {
   1988 	cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
   1989 
   1990 	if (cp) {
   1991 	    switch(*cp) {
   1992 	    case '\0':			/* not set - the default wins */
   1993 		break;
   1994 	    case '0':
   1995 	    case 'f':
   1996 	    case 'n':
   1997 		bf = FALSE;
   1998 		break;
   1999 	    case 'o':
   2000 		switch (cp[1]) {
   2001 		case 'f':
   2002 		    bf = FALSE;
   2003 		    break;
   2004 		default:
   2005 		    bf = TRUE;
   2006 		    break;
   2007 		}
   2008 		break;
   2009 	    default:
   2010 		bf = TRUE;
   2011 		break;
   2012 	    }
   2013 	    free(cp);
   2014 	}
   2015     }
   2016     return (bf);
   2017 }
   2018