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