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