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