Home | History | Annotate | Line # | Download | only in make
main.c revision 1.648
      1 /*	$NetBSD: main.c,v 1.648 2025/05/18 05:44:57 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.648 2025/05/18 05:44:57 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 PrintVar(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 doPrintVars(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 		const char *varname = ln->datum;
    890 		PrintVar(varname, expandVars);
    891 	}
    892 }
    893 
    894 static bool
    895 runTargets(void)
    896 {
    897 	GNodeList targs = LST_INIT;
    898 	bool outOfDate;		/* false if all targets up to date */
    899 
    900 	if (Lst_IsEmpty(&opts.create))
    901 		Parse_MainName(&targs);
    902 	else
    903 		Targ_FindList(&targs, &opts.create);
    904 
    905 	if (!opts.compatMake) {
    906 		if (!opts.query) {
    907 			Job_Init();
    908 			jobsRunning = true;
    909 		}
    910 
    911 		outOfDate = Make_Run(&targs);
    912 	} else {
    913 		Compat_MakeAll(&targs);
    914 		outOfDate = false;
    915 	}
    916 	Lst_Done(&targs);	/* Don't free the targets themselves. */
    917 	return outOfDate;
    918 }
    919 
    920 /*
    921  * Set up the .TARGETS variable to contain the list of targets to be created.
    922  * If none specified, make the variable empty for now, the parser will fill
    923  * in the default or .MAIN target later.
    924  */
    925 static void
    926 InitVarTargets(void)
    927 {
    928 	StringListNode *ln;
    929 
    930 	if (Lst_IsEmpty(&opts.create)) {
    931 		Global_Set(".TARGETS", "");
    932 		return;
    933 	}
    934 
    935 	for (ln = opts.create.first; ln != NULL; ln = ln->next) {
    936 		const char *name = ln->datum;
    937 		Global_Append(".TARGETS", name);
    938 	}
    939 }
    940 
    941 static void
    942 InitRandom(void)
    943 {
    944 	struct timeval tv;
    945 
    946 	gettimeofday(&tv, NULL);
    947 	srandom((unsigned)(tv.tv_sec + tv.tv_usec));
    948 }
    949 
    950 static const char *
    951 InitVarMachine(const struct utsname *utsname MAKE_ATTR_UNUSED)
    952 {
    953 	const char *machine = getenv("MACHINE");
    954 	if (machine != NULL)
    955 		return machine;
    956 
    957 #if defined(MAKE_NATIVE)
    958 	return utsname->machine;
    959 #elif defined(MAKE_MACHINE)
    960 	return MAKE_MACHINE;
    961 #else
    962 	return "unknown";
    963 #endif
    964 }
    965 
    966 static const char *
    967 InitVarMachineArch(void)
    968 {
    969 	const char *env = getenv("MACHINE_ARCH");
    970 	if (env != NULL)
    971 		return env;
    972 
    973 #ifdef MAKE_NATIVE
    974 	{
    975 		struct utsname utsname;
    976 		static char machine_arch_buf[sizeof utsname.machine];
    977 		const int mib[2] = { CTL_HW, HW_MACHINE_ARCH };
    978 		size_t len = sizeof machine_arch_buf;
    979 
    980 		if (sysctl(mib, (unsigned)__arraycount(mib),
    981 		    machine_arch_buf, &len, NULL, 0) < 0) {
    982 			(void)fprintf(stderr, "%s: sysctl failed (%s).\n",
    983 			    progname, strerror(errno));
    984 			exit(2);
    985 		}
    986 
    987 		return machine_arch_buf;
    988 	}
    989 #elif defined(MACHINE_ARCH)
    990 	return MACHINE_ARCH;
    991 #elif defined(MAKE_MACHINE_ARCH)
    992 	return MAKE_MACHINE_ARCH;
    993 #else
    994 	return "unknown";
    995 #endif
    996 }
    997 
    998 #ifndef NO_PWD_OVERRIDE
    999 /*
   1000  * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
   1001  * since the value of curdir can vary depending on how we got
   1002  * here.  That is, sitting at a shell prompt (shell that provides $PWD)
   1003  * or via subdir.mk, in which case it's likely a shell which does
   1004  * not provide it.
   1005  *
   1006  * So, to stop it breaking this case only, we ignore PWD if
   1007  * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains an expression.
   1008  */
   1009 static void
   1010 HandlePWD(const struct stat *curdir_st)
   1011 {
   1012 	char *pwd;
   1013 	FStr makeobjdir;
   1014 	struct stat pwd_st;
   1015 
   1016 	if (ignorePWD || (pwd = getenv("PWD")) == NULL)
   1017 		return;
   1018 
   1019 	if (Var_Exists(SCOPE_CMDLINE, "MAKEOBJDIRPREFIX"))
   1020 		return;
   1021 
   1022 	makeobjdir = Var_Value(SCOPE_CMDLINE, "MAKEOBJDIR");
   1023 	if (makeobjdir.str != NULL && strchr(makeobjdir.str, '$') != NULL)
   1024 		goto ignore_pwd;
   1025 
   1026 	if (stat(pwd, &pwd_st) == 0 &&
   1027 	    curdir_st->st_ino == pwd_st.st_ino &&
   1028 	    curdir_st->st_dev == pwd_st.st_dev)
   1029 		snprintf(curdir, MAXPATHLEN, "%s", pwd);
   1030 
   1031 ignore_pwd:
   1032 	FStr_Done(&makeobjdir);
   1033 }
   1034 #endif
   1035 
   1036 /*
   1037  * Find the .OBJDIR.  If MAKEOBJDIRPREFIX, or failing that, MAKEOBJDIR is set
   1038  * in the environment, try only that value and fall back to .CURDIR if it
   1039  * does not exist.
   1040  *
   1041  * Otherwise, try _PATH_OBJDIR.MACHINE-MACHINE_ARCH, _PATH_OBJDIR.MACHINE,
   1042  * and finally _PATH_OBJDIRPREFIX`pwd`, in that order.  If none of these
   1043  * paths exist, just use .CURDIR.
   1044  */
   1045 static void
   1046 InitObjdir(const char *machine, const char *machine_arch)
   1047 {
   1048 	bool writable;
   1049 
   1050 	Dir_InitCur(curdir);
   1051 	writable = GetBooleanExpr("${MAKE_OBJDIR_CHECK_WRITABLE}", true);
   1052 	(void)Main_SetObjdir(false, "%s", curdir);
   1053 
   1054 	if (!SetVarObjdir(writable, "MAKEOBJDIRPREFIX", curdir) &&
   1055 	    !SetVarObjdir(writable, "MAKEOBJDIR", "") &&
   1056 	    !Main_SetObjdir(writable, "%s.%s-%s", _PATH_OBJDIR, machine, machine_arch) &&
   1057 	    !Main_SetObjdir(writable, "%s.%s", _PATH_OBJDIR, machine) &&
   1058 	    !Main_SetObjdir(writable, "%s", _PATH_OBJDIR))
   1059 		(void)Main_SetObjdir(writable, "%s%s", _PATH_OBJDIRPREFIX, curdir);
   1060 }
   1061 
   1062 /* get rid of resource limit on file descriptors */
   1063 static void
   1064 UnlimitFiles(void)
   1065 {
   1066 #if defined(MAKE_NATIVE) || (defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE))
   1067 	struct rlimit rl;
   1068 	if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
   1069 	    rl.rlim_cur != rl.rlim_max) {
   1070 		rl.rlim_cur = rl.rlim_max;
   1071 		(void)setrlimit(RLIMIT_NOFILE, &rl);
   1072 	}
   1073 #endif
   1074 }
   1075 
   1076 static void
   1077 CmdOpts_Init(void)
   1078 {
   1079 	opts.compatMake = false;
   1080 	memset(&opts.debug, 0, sizeof(opts.debug));
   1081 	/* opts.debug_file has already been initialized earlier */
   1082 	opts.strict = false;
   1083 	opts.debugVflag = false;
   1084 	opts.checkEnvFirst = false;
   1085 	Lst_Init(&opts.makefiles);
   1086 	opts.ignoreErrors = false;	/* Pay attention to non-zero returns */
   1087 	opts.maxJobs = 1;
   1088 	opts.keepgoing = false;		/* Stop on error */
   1089 	opts.noRecursiveExecute = false; /* Execute all .MAKE targets */
   1090 	opts.noExecute = false;		/* Execute all commands */
   1091 	opts.query = false;
   1092 	opts.noBuiltins = false;	/* Read the built-in rules */
   1093 	opts.silent = false;		/* Print commands as executed */
   1094 	opts.touch = false;
   1095 	opts.printVars = PVM_NONE;
   1096 	Lst_Init(&opts.variables);
   1097 	opts.parseWarnFatal = false;
   1098 	opts.enterFlag = false;
   1099 	opts.varNoExportEnv = false;
   1100 	Lst_Init(&opts.create);
   1101 }
   1102 
   1103 /*
   1104  * Initialize MAKE and .MAKE to the path of the executable, so that it can be
   1105  * found by execvp(3) and the shells, even after a chdir.
   1106  *
   1107  * If it's a relative path and contains a '/', resolve it to an absolute path.
   1108  * Otherwise keep it as is, assuming it will be found in the PATH.
   1109  */
   1110 static void
   1111 InitVarMake(const char *argv0)
   1112 {
   1113 	const char *make = argv0;
   1114 	char pathbuf[MAXPATHLEN];
   1115 
   1116 	if (argv0[0] != '/' && strchr(argv0, '/') != NULL) {
   1117 		const char *abspath = cached_realpath(argv0, pathbuf);
   1118 		struct stat st;
   1119 		if (abspath != NULL && abspath[0] == '/' &&
   1120 		    stat(make, &st) == 0)
   1121 			make = abspath;
   1122 	}
   1123 
   1124 	Global_Set("MAKE", make);
   1125 	Global_Set(".MAKE", make);
   1126 }
   1127 
   1128 /*
   1129  * Add the directories from the colon-separated syspath to defSysIncPath.
   1130  * After returning, the contents of syspath is unspecified.
   1131  */
   1132 static void
   1133 InitDefSysIncPath(char *syspath)
   1134 {
   1135 	static char defsyspath[] = _PATH_DEFSYSPATH;
   1136 	char *start, *p;
   1137 
   1138 	/*
   1139 	 * If no user-supplied system path was given (through the -m option)
   1140 	 * add the directories from the DEFSYSPATH (more than one may be given
   1141 	 * as dir1:...:dirn) to the system include path.
   1142 	 */
   1143 	if (syspath == NULL || syspath[0] == '\0')
   1144 		syspath = defsyspath;
   1145 	else
   1146 		syspath = bmake_strdup(syspath);
   1147 
   1148 	for (start = syspath; *start != '\0'; start = p) {
   1149 		for (p = start; *p != '\0' && *p != ':'; p++)
   1150 			continue;
   1151 		if (*p == ':')
   1152 			*p++ = '\0';
   1153 
   1154 		/* look for magic parent directory search string */
   1155 		if (strncmp(start, ".../", 4) == 0) {
   1156 			char *dir = Dir_FindHereOrAbove(curdir, start + 4);
   1157 			if (dir != NULL) {
   1158 				(void)SearchPath_Add(defSysIncPath, dir);
   1159 				free(dir);
   1160 			}
   1161 		} else {
   1162 			(void)SearchPath_Add(defSysIncPath, start);
   1163 		}
   1164 	}
   1165 
   1166 	if (syspath != defsyspath)
   1167 		free(syspath);
   1168 }
   1169 
   1170 static void
   1171 ReadBuiltinRules(void)
   1172 {
   1173 	StringListNode *ln;
   1174 	StringList sysMkFiles = LST_INIT;
   1175 
   1176 	SearchPath_Expand(
   1177 	    Lst_IsEmpty(&sysIncPath->dirs) ? defSysIncPath : sysIncPath,
   1178 	    _PATH_DEFSYSMK,
   1179 	    &sysMkFiles);
   1180 	if (Lst_IsEmpty(&sysMkFiles))
   1181 		Fatal("%s: no system rules (%s).", progname, _PATH_DEFSYSMK);
   1182 
   1183 	for (ln = sysMkFiles.first; ln != NULL; ln = ln->next)
   1184 		if (ReadMakefile(ln->datum))
   1185 			break;
   1186 
   1187 	if (ln == NULL)
   1188 		Fatal("%s: cannot open %s.",
   1189 		    progname, (const char *)sysMkFiles.first->datum);
   1190 
   1191 	Lst_DoneFree(&sysMkFiles);
   1192 }
   1193 
   1194 static void
   1195 InitMaxJobs(void)
   1196 {
   1197 	char *value;
   1198 	int n;
   1199 
   1200 	if (forceJobs || opts.compatMake ||
   1201 	    !Var_Exists(SCOPE_GLOBAL, ".MAKE.JOBS"))
   1202 		return;
   1203 
   1204 	value = Var_Subst("${.MAKE.JOBS}", SCOPE_GLOBAL, VARE_EVAL);
   1205 	/* TODO: handle errors */
   1206 	n = (int)strtol(value, NULL, 0);
   1207 	if (n < 1) {
   1208 		(void)fprintf(stderr,
   1209 		    "%s: illegal value for .MAKE.JOBS "
   1210 		    "-- must be positive integer!\n",
   1211 		    progname);
   1212 		exit(2);	/* Not 1 so -q can distinguish error */
   1213 	}
   1214 
   1215 	if (n != opts.maxJobs) {
   1216 		Global_Append(MAKEFLAGS, "-j");
   1217 		Global_Append(MAKEFLAGS, value);
   1218 	}
   1219 
   1220 	opts.maxJobs = n;
   1221 	maxJobTokens = opts.maxJobs;
   1222 	forceJobs = true;
   1223 	free(value);
   1224 }
   1225 
   1226 /*
   1227  * For compatibility, look at the directories in the VPATH variable
   1228  * and add them to the search path, if the variable is defined. The
   1229  * variable's value is in the same format as the PATH environment
   1230  * variable, i.e. <directory>:<directory>:<directory>...
   1231  */
   1232 static void
   1233 InitVpath(void)
   1234 {
   1235 	char *vpath, savec, *path;
   1236 	if (!Var_Exists(SCOPE_CMDLINE, "VPATH"))
   1237 		return;
   1238 
   1239 	vpath = Var_Subst("${VPATH}", SCOPE_CMDLINE, VARE_EVAL);
   1240 	/* TODO: handle errors */
   1241 	path = vpath;
   1242 	do {
   1243 		char *p;
   1244 		/* skip to end of directory */
   1245 		for (p = path; *p != ':' && *p != '\0'; p++)
   1246 			continue;
   1247 		/* Save terminator character so know when to stop */
   1248 		savec = *p;
   1249 		*p = '\0';
   1250 		/* Add directory to search path */
   1251 		(void)SearchPath_Add(&dirSearchPath, path);
   1252 		*p = savec;
   1253 		path = p + 1;
   1254 	} while (savec == ':');
   1255 	free(vpath);
   1256 }
   1257 
   1258 static void
   1259 ReadAllMakefiles(const StringList *makefiles)
   1260 {
   1261 	StringListNode *ln;
   1262 
   1263 	for (ln = makefiles->first; ln != NULL; ln = ln->next) {
   1264 		const char *fname = ln->datum;
   1265 		if (!ReadMakefile(fname))
   1266 			Fatal("%s: cannot open %s.", progname, fname);
   1267 	}
   1268 }
   1269 
   1270 static void
   1271 ReadFirstDefaultMakefile(void)
   1272 {
   1273 	StringList makefiles = LST_INIT;
   1274 	StringListNode *ln;
   1275 	char *prefs = Var_Subst("${.MAKE.MAKEFILE_PREFERENCE}",
   1276 	    SCOPE_CMDLINE, VARE_EVAL);
   1277 	/* TODO: handle errors */
   1278 
   1279 	AppendWords(&makefiles, prefs);
   1280 
   1281 	for (ln = makefiles.first; ln != NULL; ln = ln->next)
   1282 		if (ReadMakefile(ln->datum))
   1283 			break;
   1284 
   1285 	Lst_Done(&makefiles);
   1286 	free(prefs);
   1287 }
   1288 
   1289 /*
   1290  * Initialize variables such as MAKE, MACHINE, .MAKEFLAGS.
   1291  * Initialize a few modules.
   1292  * Parse the arguments from MAKEFLAGS and the command line.
   1293  */
   1294 static void
   1295 main_Init(int argc, char **argv)
   1296 {
   1297 	struct stat sa;
   1298 	const char *machine;
   1299 	const char *machine_arch;
   1300 	char *syspath = getenv("MAKESYSPATH");
   1301 	struct utsname utsname;
   1302 
   1303 	/* default to writing debug to stderr */
   1304 	opts.debug_file = stderr;
   1305 
   1306 	Str_Intern_Init();
   1307 	HashTable_Init(&cached_realpaths);
   1308 
   1309 #ifdef SIGINFO
   1310 	(void)bmake_signal(SIGINFO, siginfo);
   1311 #endif
   1312 
   1313 	InitRandom();
   1314 
   1315 	progname = str_basename(argv[0]);
   1316 
   1317 	UnlimitFiles();
   1318 
   1319 	if (uname(&utsname) == -1) {
   1320 		(void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
   1321 		    strerror(errno));
   1322 		exit(2);
   1323 	}
   1324 
   1325 	machine = InitVarMachine(&utsname);
   1326 	machine_arch = InitVarMachineArch();
   1327 
   1328 	myPid = getpid();
   1329 
   1330 	/* Just in case MAKEOBJDIR wants us to do something tricky. */
   1331 	Targ_Init();
   1332 	Global_Set_ReadOnly(".MAKE.OS", utsname.sysname);
   1333 	Global_Set("MACHINE", machine);
   1334 	Global_Set("MACHINE_ARCH", machine_arch);
   1335 #ifdef MAKE_VERSION
   1336 	Global_Set("MAKE_VERSION", MAKE_VERSION);
   1337 #endif
   1338 	Global_Set_ReadOnly(".newline", "\n");
   1339 #ifndef MAKEFILE_PREFERENCE_LIST
   1340 	/* This is the traditional preference for makefiles. */
   1341 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
   1342 #endif
   1343 	Global_Set(".MAKE.MAKEFILE_PREFERENCE", MAKEFILE_PREFERENCE_LIST);
   1344 	Global_Set(".MAKE.DEPENDFILE", ".depend");
   1345 	/* Tell makefiles like jobs.mk whether we support -jC */
   1346 #ifdef _SC_NPROCESSORS_ONLN
   1347 	Global_Set_ReadOnly(".MAKE.JOBS.C", "yes");
   1348 #else
   1349 	Global_Set_ReadOnly(".MAKE.JOBS.C", "no");
   1350 #endif
   1351 
   1352 	CmdOpts_Init();
   1353 	allPrecious = false;	/* Remove targets when interrupted */
   1354 	deleteOnError = false;	/* Historical default behavior */
   1355 	jobsRunning = false;
   1356 
   1357 	maxJobTokens = opts.maxJobs;
   1358 	ignorePWD = false;
   1359 
   1360 	/*
   1361 	 * Initialize the parsing, directory and variable modules to prepare
   1362 	 * for the reading of inclusion paths and variable settings on the
   1363 	 * command line
   1364 	 */
   1365 
   1366 	/*
   1367 	 * Initialize various variables.
   1368 	 *	MAKE also gets this name, for compatibility
   1369 	 *	.MAKEFLAGS gets set to the empty string just in case.
   1370 	 *	MFLAGS also gets initialized empty, for compatibility.
   1371 	 */
   1372 	Parse_Init();
   1373 	InitVarMake(argv[0]);
   1374 	Global_Set(MAKEFLAGS, "");
   1375 	Global_Set(".MAKEOVERRIDES", "");
   1376 	Global_Set("MFLAGS", "");
   1377 	Global_Set(".ALLTARGETS", "");
   1378 	Global_Set_ReadOnly(".MAKE.LEVEL.ENV", MAKE_LEVEL_ENV);
   1379 
   1380 	/* Set some other useful variables. */
   1381 	{
   1382 		char buf[64];
   1383 		const char *ep = getenv(MAKE_LEVEL_ENV);
   1384 
   1385 		makelevel = ep != NULL && ep[0] != '\0' ? atoi(ep) : 0;
   1386 		if (makelevel < 0)
   1387 			makelevel = 0;
   1388 		snprintf(buf, sizeof buf, "%d", makelevel);
   1389 		Global_Set(".MAKE.LEVEL", buf);
   1390 		snprintf(buf, sizeof buf, "%u", myPid);
   1391 		Global_Set_ReadOnly(".MAKE.PID", buf);
   1392 		snprintf(buf, sizeof buf, "%u", getppid());
   1393 		Global_Set_ReadOnly(".MAKE.PPID", buf);
   1394 		snprintf(buf, sizeof buf, "%u", getuid());
   1395 		Global_Set_ReadOnly(".MAKE.UID", buf);
   1396 		snprintf(buf, sizeof buf, "%u", getgid());
   1397 		Global_Set_ReadOnly(".MAKE.GID", buf);
   1398 	}
   1399 	if (makelevel > 0) {
   1400 		char pn[1024];
   1401 		snprintf(pn, sizeof pn, "%s[%d]", progname, makelevel);
   1402 		progname = bmake_strdup(pn);
   1403 	}
   1404 
   1405 #ifdef USE_META
   1406 	meta_init();
   1407 #endif
   1408 	Dir_Init();
   1409 
   1410 	{
   1411 		char *makeflags = explode(getenv("MAKEFLAGS"));
   1412 		Main_ParseArgLine(makeflags);
   1413 		free(makeflags);
   1414 	}
   1415 
   1416 	if (getcwd(curdir, MAXPATHLEN) == NULL) {
   1417 		(void)fprintf(stderr, "%s: getcwd: %s.\n",
   1418 		    progname, strerror(errno));
   1419 		exit(2);
   1420 	}
   1421 
   1422 	MainParseArgs(argc, argv);
   1423 
   1424 	if (opts.enterFlag)
   1425 		printf("%s: Entering directory `%s'\n", progname, curdir);
   1426 
   1427 	if (stat(curdir, &sa) == -1) {
   1428 		(void)fprintf(stderr, "%s: %s: %s.\n",
   1429 		    progname, curdir, strerror(errno));
   1430 		exit(2);
   1431 	}
   1432 
   1433 #ifndef NO_PWD_OVERRIDE
   1434 	HandlePWD(&sa);
   1435 #endif
   1436 	Global_Set(".CURDIR", curdir);
   1437 
   1438 	InitObjdir(machine, machine_arch);
   1439 
   1440 	Arch_Init();
   1441 	Suff_Init();
   1442 	Trace_Init(tracefile);
   1443 
   1444 	defaultNode = NULL;
   1445 	(void)time(&now);
   1446 
   1447 	Trace_Log(MAKESTART, NULL);
   1448 
   1449 	InitVarTargets();
   1450 
   1451 	InitDefSysIncPath(syspath);
   1452 }
   1453 
   1454 /*
   1455  * Read the system makefile followed by either makefile, Makefile or the
   1456  * files given by the -f option. Exit on parse errors.
   1457  */
   1458 static void
   1459 main_ReadFiles(void)
   1460 {
   1461 
   1462 	if (Lst_IsEmpty(&sysIncPath->dirs))
   1463 		SearchPath_AddAll(sysIncPath, defSysIncPath);
   1464 
   1465 	Dir_SetSYSPATH();
   1466 	if (!opts.noBuiltins)
   1467 		ReadBuiltinRules();
   1468 
   1469 	posix_state = PS_MAYBE_NEXT_LINE;
   1470 	if (!Lst_IsEmpty(&opts.makefiles))
   1471 		ReadAllMakefiles(&opts.makefiles);
   1472 	else
   1473 		ReadFirstDefaultMakefile();
   1474 }
   1475 
   1476 /* Compute the dependency graph. */
   1477 static void
   1478 main_PrepareMaking(void)
   1479 {
   1480 	/* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
   1481 	if (!opts.noBuiltins || opts.printVars == PVM_NONE) {
   1482 		makeDependfile = Var_Subst("${.MAKE.DEPENDFILE}",
   1483 		    SCOPE_CMDLINE, VARE_EVAL);
   1484 		if (makeDependfile[0] != '\0') {
   1485 			/* TODO: handle errors */
   1486 			doing_depend = true;
   1487 			(void)ReadMakefile(makeDependfile);
   1488 			doing_depend = false;
   1489 		}
   1490 	}
   1491 
   1492 	if (enterFlagObj)
   1493 		printf("%s: Entering directory `%s'\n", progname, objdir);
   1494 
   1495 	MakeMode();
   1496 
   1497 	{
   1498 		FStr makeflags = Var_Value(SCOPE_GLOBAL, MAKEFLAGS);
   1499 		Global_Append("MFLAGS", makeflags.str);
   1500 		FStr_Done(&makeflags);
   1501 	}
   1502 
   1503 	InitMaxJobs();
   1504 
   1505 	if (!opts.compatMake && !forceJobs)
   1506 		opts.compatMake = true;
   1507 
   1508 	if (!opts.compatMake)
   1509 		TokenPool_Init(maxJobTokens, tokenPoolReader, tokenPoolWriter);
   1510 	DEBUG5(JOB, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
   1511 	    tokenPoolReader, tokenPoolWriter, opts.maxJobs, maxJobTokens,
   1512 	    opts.compatMake ? 1 : 0);
   1513 
   1514 	if (opts.printVars == PVM_NONE)
   1515 		Main_ExportMAKEFLAGS(true);	/* initial export */
   1516 
   1517 	InitVpath();
   1518 
   1519 	/*
   1520 	 * Now that all search paths have been read for suffixes et al, it's
   1521 	 * time to add the default search path to their lists...
   1522 	 */
   1523 	Suff_ExtendPaths();
   1524 
   1525 	/*
   1526 	 * Propagate attributes through :: dependency lists.
   1527 	 */
   1528 	Targ_Propagate();
   1529 
   1530 	/* print the initial graph, if the user requested it */
   1531 	if (DEBUG(GRAPH1))
   1532 		Targ_PrintGraph(1);
   1533 }
   1534 
   1535 /*
   1536  * Make the targets, or print variables.
   1537  * Return whether any of the targets is out-of-date.
   1538  */
   1539 static bool
   1540 main_Run(void)
   1541 {
   1542 	if (opts.printVars != PVM_NONE) {
   1543 		doPrintVars();
   1544 		return false;
   1545 	} else {
   1546 		return runTargets();
   1547 	}
   1548 }
   1549 
   1550 /* Clean up after making the targets. */
   1551 static void
   1552 main_CleanUp(void)
   1553 {
   1554 #ifdef CLEANUP
   1555 	Lst_DoneFree(&opts.variables);
   1556 	Lst_DoneFree(&opts.makefiles);
   1557 	Lst_DoneFree(&opts.create);
   1558 #endif
   1559 
   1560 	if (DEBUG(GRAPH2))
   1561 		Targ_PrintGraph(2);
   1562 
   1563 	Trace_Log(MAKEEND, NULL);
   1564 
   1565 	if (enterFlagObj)
   1566 		printf("%s: Leaving directory `%s'\n", progname, objdir);
   1567 	if (opts.enterFlag)
   1568 		printf("%s: Leaving directory `%s'\n", progname, curdir);
   1569 
   1570 	Var_Stats();
   1571 	Targ_Stats();
   1572 
   1573 #ifdef USE_META
   1574 	meta_finish();
   1575 #endif
   1576 #ifdef CLEANUP
   1577 	Suff_End();
   1578 	Targ_End();
   1579 	Arch_End();
   1580 	Parse_End();
   1581 	Dir_End();
   1582 	Job_End();
   1583 #endif
   1584 	Trace_End();
   1585 #ifdef CLEANUP
   1586 	Str_Intern_End();
   1587 #endif
   1588 }
   1589 
   1590 /* Determine the exit code. */
   1591 static int
   1592 main_Exit(bool outOfDate)
   1593 {
   1594 	if ((opts.strict && main_errors > 0) || parseErrors > 0)
   1595 		return 2;	/* Not 1 so -q can distinguish error */
   1596 	return outOfDate ? 1 : 0;
   1597 }
   1598 
   1599 int
   1600 main(int argc, char **argv)
   1601 {
   1602 	bool outOfDate;
   1603 
   1604 	main_Init(argc, argv);
   1605 	main_ReadFiles();
   1606 	main_PrepareMaking();
   1607 	outOfDate = main_Run();
   1608 	main_CleanUp();
   1609 	return main_Exit(outOfDate);
   1610 }
   1611 
   1612 /*
   1613  * Open and parse the given makefile, with all its side effects.
   1614  * Return false if the file could not be opened.
   1615  */
   1616 static bool
   1617 ReadMakefile(const char *fname)
   1618 {
   1619 	int fd;
   1620 	char *name, *path = NULL;
   1621 
   1622 	if (strcmp(fname, "-") == 0) {
   1623 		Parse_File("(stdin)", -1);
   1624 		Var_Set(SCOPE_INTERNAL, "MAKEFILE", "");
   1625 	} else {
   1626 		if (strncmp(fname, ".../", 4) == 0) {
   1627 			name = Dir_FindHereOrAbove(curdir, fname + 4);
   1628 			if (name != NULL) {
   1629 				/* Dir_FindHereOrAbove returns dirname */
   1630 				path = str_concat3(name, "/",
   1631 				    str_basename(fname));
   1632 				free(name);
   1633 				fd = open(path, O_RDONLY);
   1634 				if (fd != -1) {
   1635 					fname = path;
   1636 					goto found;
   1637 				}
   1638 			}
   1639 		}
   1640 		/* if we've chdir'd, rebuild the path name */
   1641 		if (strcmp(curdir, objdir) != 0 && *fname != '/') {
   1642 			path = str_concat3(curdir, "/", fname);
   1643 			fd = open(path, O_RDONLY);
   1644 			if (fd != -1) {
   1645 				fname = path;
   1646 				goto found;
   1647 			}
   1648 			free(path);
   1649 
   1650 			/* If curdir failed, try objdir (ala .depend) */
   1651 			path = str_concat3(objdir, "/", fname);
   1652 			fd = open(path, O_RDONLY);
   1653 			if (fd != -1) {
   1654 				fname = path;
   1655 				goto found;
   1656 			}
   1657 		} else {
   1658 			fd = open(fname, O_RDONLY);
   1659 			if (fd != -1)
   1660 				goto found;
   1661 		}
   1662 		/* look in -I and system include directories. */
   1663 		name = Dir_FindFile(fname, parseIncPath);
   1664 		if (name == NULL) {
   1665 			SearchPath *sysInc = Lst_IsEmpty(&sysIncPath->dirs)
   1666 			    ? defSysIncPath : sysIncPath;
   1667 			name = Dir_FindFile(fname, sysInc);
   1668 		}
   1669 		if (name == NULL || (fd = open(name, O_RDONLY)) == -1) {
   1670 			free(name);
   1671 			free(path);
   1672 			return false;
   1673 		}
   1674 		fname = name;
   1675 		/*
   1676 		 * set the MAKEFILE variable desired by System V fans -- the
   1677 		 * placement of the setting here means it gets set to the last
   1678 		 * makefile specified, as it is set by SysV make.
   1679 		 */
   1680 found:
   1681 		if (!doing_depend)
   1682 			Var_Set(SCOPE_INTERNAL, "MAKEFILE", fname);
   1683 		Parse_File(fname, fd);
   1684 	}
   1685 	free(path);
   1686 	return true;
   1687 }
   1688 
   1689 /* populate av for Cmd_Exec and Compat_RunCommand */
   1690 int
   1691 Cmd_Argv(const char *cmd, size_t cmd_len, const char **av, size_t avsz,
   1692     char *cmd_file, size_t cmd_filesz, bool eflag, bool xflag)
   1693 {
   1694 	int ac = 0;
   1695 	int cmd_fd = -1;
   1696 
   1697 	if (shellPath == NULL)
   1698 		Shell_Init();
   1699 
   1700 	if (cmd_file != NULL) {
   1701 		if (cmd_len == 0)
   1702 			cmd_len = strlen(cmd);
   1703 
   1704 		if (cmd_len > MAKE_CMDLEN_LIMIT) {
   1705 			cmd_fd = mkTempFile(NULL, cmd_file, cmd_filesz);
   1706 			if (cmd_fd >= 0) {
   1707 				ssize_t n;
   1708 
   1709 				n = write(cmd_fd, cmd, cmd_len);
   1710 				close(cmd_fd);
   1711 				if (n < (ssize_t)cmd_len) {
   1712 					unlink(cmd_file);
   1713 					cmd_fd = -1;
   1714 				}
   1715 			}
   1716 		} else
   1717 			cmd_file[0] = '\0';
   1718 	}
   1719 
   1720 	if (avsz < 4 || (eflag && avsz < 5))
   1721 		return -1;
   1722 
   1723 	/* The following works for any of the builtin shell specs. */
   1724 	av[ac++] = shellPath;
   1725 	if (eflag)
   1726 		av[ac++] = shellErrFlag;
   1727 	if (cmd_fd >= 0) {
   1728 		if (xflag)
   1729 			av[ac++] = "-x";
   1730 		av[ac++] = cmd_file;
   1731 	} else {
   1732 		av[ac++] = xflag ? "-xc" : "-c";
   1733 		av[ac++] = cmd;
   1734 	}
   1735 	av[ac] = NULL;
   1736 	return ac;
   1737 }
   1738 
   1739 /*
   1740  * Execute the command in cmd, and return its output (only stdout, not
   1741  * stderr, possibly empty).  In the output, replace newlines with spaces.
   1742  */
   1743 char *
   1744 Cmd_Exec(const char *cmd, char **error)
   1745 {
   1746 	const char *args[4];	/* Arguments for invoking the shell */
   1747 	int pipefds[2];
   1748 	int cpid;		/* Child PID */
   1749 	int pid;		/* PID from wait() */
   1750 	int status;		/* command exit status */
   1751 	Buffer buf;		/* buffer to store the result */
   1752 	ssize_t bytes_read;
   1753 	char *output;
   1754 	char *p;
   1755 	int saved_errno;
   1756 	char cmd_file[MAXPATHLEN];
   1757 
   1758 	DEBUG1(VAR, "Capturing the output of command \"%s\"\n", cmd);
   1759 
   1760 	if (Cmd_Argv(cmd, 0, args, 4, cmd_file, sizeof(cmd_file), false, false) < 0
   1761 	    || pipe(pipefds) == -1) {
   1762 		*error = str_concat3(
   1763 		    "Couldn't create pipe for \"", cmd, "\"");
   1764 		return bmake_strdup("");
   1765 	}
   1766 
   1767 	Var_ReexportVars(SCOPE_GLOBAL);
   1768 
   1769 	switch (cpid = FORK_FUNCTION()) {
   1770 	case 0:
   1771 		(void)close(pipefds[0]);
   1772 		(void)dup2(pipefds[1], STDOUT_FILENO);
   1773 		(void)close(pipefds[1]);
   1774 
   1775 		(void)execv(shellPath, UNCONST(args));
   1776 		_exit(1);
   1777 		/* NOTREACHED */
   1778 
   1779 	case -1:
   1780 		*error = str_concat3("Couldn't exec \"", cmd, "\"");
   1781 		return bmake_strdup("");
   1782 	}
   1783 
   1784 	(void)close(pipefds[1]);	/* No need for the writing half */
   1785 
   1786 	saved_errno = 0;
   1787 	Buf_Init(&buf);
   1788 
   1789 	do {
   1790 		char result[BUFSIZ];
   1791 		bytes_read = read(pipefds[0], result, sizeof result);
   1792 		if (bytes_read > 0)
   1793 			Buf_AddBytes(&buf, result, (size_t)bytes_read);
   1794 	} while (bytes_read > 0 || (bytes_read == -1 && errno == EINTR));
   1795 	if (bytes_read == -1)
   1796 		saved_errno = errno;
   1797 
   1798 	(void)close(pipefds[0]); /* Close the input side of the pipe. */
   1799 
   1800 	while ((pid = waitpid(cpid, &status, 0)) != cpid && pid >= 0)
   1801 		JobReapChild(pid, status, false);
   1802 
   1803 	if (Buf_EndsWith(&buf, '\n'))
   1804 		buf.data[buf.len - 1] = '\0';
   1805 
   1806 	output = Buf_DoneData(&buf);
   1807 	for (p = output; *p != '\0'; p++)
   1808 		if (*p == '\n')
   1809 			*p = ' ';
   1810 
   1811 	if (WIFSIGNALED(status))
   1812 		*error = str_concat3("\"", cmd, "\" exited on a signal");
   1813 	else if (WEXITSTATUS(status) != 0) {
   1814 		Buffer errBuf;
   1815 		Buf_Init(&errBuf);
   1816 		Buf_AddStr(&errBuf, "Command \"");
   1817 		Buf_AddStr(&errBuf, cmd);
   1818 		Buf_AddStr(&errBuf, "\" exited with status ");
   1819 		Buf_AddInt(&errBuf, WEXITSTATUS(status));
   1820 		*error = Buf_DoneData(&errBuf);
   1821 	} else if (saved_errno != 0)
   1822 		*error = str_concat3(
   1823 		    "Couldn't read shell's output for \"", cmd, "\"");
   1824 	else
   1825 		*error = NULL;
   1826 	if (cmd_file[0] != '\0')
   1827 		unlink(cmd_file);
   1828 	return output;
   1829 }
   1830 
   1831 /*
   1832  * Print a printf-style error message.
   1833  *
   1834  * In default mode, this error message has no consequences, for compatibility
   1835  * reasons, in particular it does not affect the exit status.  Only in lint
   1836  * mode (-dL) it does.
   1837  */
   1838 void
   1839 Error(const char *fmt, ...)
   1840 {
   1841 	va_list ap;
   1842 	FILE *f;
   1843 
   1844 	f = opts.debug_file;
   1845 	if (f == stdout)
   1846 		f = stderr;
   1847 	(void)fflush(stdout);
   1848 
   1849 	for (;;) {
   1850 		fprintf(f, "%s: ", progname);
   1851 		va_start(ap, fmt);
   1852 		(void)vfprintf(f, fmt, ap);
   1853 		va_end(ap);
   1854 		(void)fprintf(f, "\n");
   1855 		(void)fflush(f);
   1856 		if (f == stderr)
   1857 			break;
   1858 		f = stderr;
   1859 	}
   1860 	main_errors++;
   1861 }
   1862 
   1863 /*
   1864  * Wait for any running jobs to finish, then produce an error message,
   1865  * finally exit immediately.
   1866  *
   1867  * Exiting immediately differs from Parse_Error, which exits only after the
   1868  * current top-level makefile has been parsed completely.
   1869  */
   1870 void
   1871 Fatal(const char *fmt, ...)
   1872 {
   1873 	va_list ap;
   1874 
   1875 	if (jobsRunning)
   1876 		Job_Wait();
   1877 
   1878 	(void)fflush(stdout);
   1879 	fprintf(stderr, "%s: ", progname);
   1880 	va_start(ap, fmt);
   1881 	(void)vfprintf(stderr, fmt, ap);
   1882 	va_end(ap);
   1883 	(void)fprintf(stderr, "\n");
   1884 	(void)fflush(stderr);
   1885 	PrintStackTrace(true);
   1886 
   1887 	PrintOnError(NULL, "\n");
   1888 
   1889 	if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
   1890 		Targ_PrintGraph(2);
   1891 	Trace_Log(MAKEERROR, NULL);
   1892 	exit(2);		/* Not 1 so -q can distinguish error */
   1893 }
   1894 
   1895 /*
   1896  * Major exception once jobs are being created.
   1897  * Kills all jobs, prints a message and exits.
   1898  */
   1899 void
   1900 Punt(const char *fmt, ...)
   1901 {
   1902 	va_list ap;
   1903 
   1904 	(void)fflush(stdout);
   1905 	(void)fprintf(stderr, "%s: ", progname);
   1906 	va_start(ap, fmt);
   1907 	(void)vfprintf(stderr, fmt, ap);
   1908 	va_end(ap);
   1909 	(void)fprintf(stderr, "\n");
   1910 	(void)fflush(stderr);
   1911 
   1912 	PrintOnError(NULL, "\n");
   1913 
   1914 	DieHorribly();
   1915 }
   1916 
   1917 /* Exit without giving a message. */
   1918 void
   1919 DieHorribly(void)
   1920 {
   1921 	if (jobsRunning)
   1922 		Job_AbortAll();
   1923 	if (DEBUG(GRAPH2))
   1924 		Targ_PrintGraph(2);
   1925 	Trace_Log(MAKEERROR, NULL);
   1926 	exit(2);		/* Not 1 so -q can distinguish error */
   1927 }
   1928 
   1929 int
   1930 unlink_file(const char *file)
   1931 {
   1932 	struct stat st;
   1933 
   1934 	if (lstat(file, &st) == -1)
   1935 		return -1;
   1936 
   1937 	if (S_ISDIR(st.st_mode)) {
   1938 		/*
   1939 		 * POSIX says for unlink: "The path argument shall not name
   1940 		 * a directory unless [...]".
   1941 		 */
   1942 		errno = EISDIR;
   1943 		return -1;
   1944 	}
   1945 	return unlink(file);
   1946 }
   1947 
   1948 static void
   1949 write_all(int fd, const void *data, size_t n)
   1950 {
   1951 	const char *mem = data;
   1952 
   1953 	while (n > 0) {
   1954 		ssize_t written = write(fd, mem, n);
   1955 		/* XXX: Should this EAGAIN be EINTR? */
   1956 		if (written == -1 && errno == EAGAIN)
   1957 			continue;
   1958 		if (written == -1)
   1959 			break;
   1960 		mem += written;
   1961 		n -= (size_t)written;
   1962 	}
   1963 }
   1964 
   1965 /* Print why exec failed, avoiding stdio. */
   1966 void MAKE_ATTR_DEAD
   1967 execDie(const char *func, const char *arg)
   1968 {
   1969 	char msg[1024];
   1970 	int len;
   1971 
   1972 	len = snprintf(msg, sizeof(msg), "%s: %s(%s) failed (%s)\n",
   1973 	    progname, func, arg, strerror(errno));
   1974 	write_all(STDERR_FILENO, msg, (size_t)len);
   1975 	_exit(1);
   1976 }
   1977 
   1978 static void
   1979 purge_relative_cached_realpaths(void)
   1980 {
   1981 	HashIter hi;
   1982 	bool more;
   1983 
   1984 	HashIter_Init(&hi, &cached_realpaths);
   1985 	more = HashIter_Next(&hi);
   1986 	while (more) {
   1987 		HashEntry *he = hi.entry;
   1988 		more = HashIter_Next(&hi);
   1989 		if (he->key[0] != '/') {
   1990 			DEBUG1(DIR, "cached_realpath: purging %s\n", he->key);
   1991 			free(he->value);
   1992 			HashTable_DeleteEntry(&cached_realpaths, he);
   1993 		}
   1994 	}
   1995 }
   1996 
   1997 const char *
   1998 cached_realpath(const char *pathname, char *resolved)
   1999 {
   2000 	const char *rp;
   2001 
   2002 	if (pathname == NULL || pathname[0] == '\0')
   2003 		return NULL;
   2004 
   2005 	rp = HashTable_FindValue(&cached_realpaths, pathname);
   2006 	if (rp != NULL) {
   2007 		snprintf(resolved, MAXPATHLEN, "%s", rp);
   2008 		return resolved;
   2009 	}
   2010 
   2011 	rp = realpath(pathname, resolved);
   2012 	if (rp != NULL) {
   2013 		HashTable_Set(&cached_realpaths, pathname, bmake_strdup(rp));
   2014 		DEBUG2(DIR, "cached_realpath: %s -> %s\n", pathname, rp);
   2015 		return resolved;
   2016 	}
   2017 
   2018 	/* should we negative-cache? */
   2019 	return NULL;
   2020 }
   2021 
   2022 /*
   2023  * Return true if we should die without noise.
   2024  * For example our failing child was a sub-make or failure happened elsewhere.
   2025  */
   2026 bool
   2027 shouldDieQuietly(GNode *gn, int bf)
   2028 {
   2029 	static int quietly = -1;
   2030 
   2031 	if (quietly < 0) {
   2032 		if (DEBUG(JOB) ||
   2033 		    !GetBooleanExpr("${.MAKE.DIE_QUIETLY}", true))
   2034 			quietly = 0;
   2035 		else if (bf >= 0)
   2036 			quietly = bf;
   2037 		else
   2038 			quietly = (gn != NULL && (gn->type & OP_MAKE)) ? 1 : 0;
   2039 	}
   2040 	return quietly != 0;
   2041 }
   2042 
   2043 static void
   2044 SetErrorVars(GNode *gn)
   2045 {
   2046 	StringListNode *ln;
   2047 	char sts[16];
   2048 
   2049 	/*
   2050 	 * We can print this even if there is no .ERROR target.
   2051 	 */
   2052 	snprintf(sts, sizeof(sts), "%d", gn->exit_status);
   2053 	Global_Set(".ERROR_EXIT", sts);
   2054 	Global_Set(".ERROR_TARGET", gn->name);
   2055 	Global_Delete(".ERROR_CMD");
   2056 
   2057 	for (ln = gn->commands.first; ln != NULL; ln = ln->next) {
   2058 		const char *cmd = ln->datum;
   2059 
   2060 		if (cmd == NULL)
   2061 			break;
   2062 		Global_Append(".ERROR_CMD", cmd);
   2063 	}
   2064 }
   2065 
   2066 /*
   2067  * Print some helpful information in case of an error.
   2068  * The caller should exit soon after calling this function.
   2069  */
   2070 void
   2071 PrintOnError(GNode *gn, const char *msg)
   2072 {
   2073 	static GNode *errorNode = NULL;
   2074 	StringListNode *ln;
   2075 
   2076 	if (DEBUG(HASH)) {
   2077 		Targ_Stats();
   2078 		Var_Stats();
   2079 	}
   2080 
   2081 	if (errorNode != NULL)
   2082 		return;		/* we've been here! */
   2083 
   2084 	printf("%s%s: stopped", msg, progname);
   2085 	ln = opts.create.first;
   2086 	if (ln != NULL || mainNode != NULL) {
   2087 		printf(" making \"");
   2088 		if (ln != NULL) {
   2089 			printf("%s", (const char *)ln->datum);
   2090 			for (ln = ln->next; ln != NULL; ln = ln->next)
   2091 				printf(" %s", (const char *)ln->datum);
   2092 		} else
   2093 			printf("%s", mainNode->name);
   2094 		printf("\"");
   2095 	}
   2096 	printf(" in %s\n", curdir);
   2097 
   2098 	/* we generally want to keep quiet if a sub-make died */
   2099 	if (shouldDieQuietly(gn, -1))
   2100 		return;
   2101 
   2102 	if (gn != NULL)
   2103 		SetErrorVars(gn);
   2104 
   2105 	{
   2106 		char *errorVarsValues;
   2107 		enum PosixState p_s = posix_state;
   2108 
   2109 		posix_state = PS_TOO_LATE;
   2110 		errorVarsValues = Var_Subst(
   2111 		    "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
   2112 		    SCOPE_GLOBAL, VARE_EVAL);
   2113 		/* TODO: handle errors */
   2114 		printf("%s", errorVarsValues);
   2115 		free(errorVarsValues);
   2116 		posix_state = p_s;
   2117 	}
   2118 
   2119 	fflush(stdout);
   2120 
   2121 	/*
   2122 	 * Finally, see if there is a .ERROR target, and run it if so.
   2123 	 */
   2124 	errorNode = Targ_FindNode(".ERROR");
   2125 	if (errorNode != NULL) {
   2126 		errorNode->type |= OP_SPECIAL;
   2127 		Compat_Make(errorNode, errorNode);
   2128 	}
   2129 }
   2130 
   2131 void
   2132 Main_ExportMAKEFLAGS(bool first)
   2133 {
   2134 	static bool once = true;
   2135 	enum PosixState p_s;
   2136 	char *flags;
   2137 
   2138 	if (once != first)
   2139 		return;
   2140 	once = false;
   2141 
   2142 	p_s = posix_state;
   2143 	posix_state = PS_TOO_LATE;
   2144 	flags = Var_Subst(
   2145 	    "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
   2146 	    SCOPE_CMDLINE, VARE_EVAL);
   2147 	/* TODO: handle errors */
   2148 	if (flags[0] != '\0')
   2149 		setenv("MAKEFLAGS", flags, 1);
   2150 	free(flags);
   2151 	posix_state = p_s;
   2152 }
   2153 
   2154 char *
   2155 getTmpdir(void)
   2156 {
   2157 	static char *tmpdir = NULL;
   2158 	struct stat st;
   2159 
   2160 	if (tmpdir != NULL)
   2161 		return tmpdir;
   2162 
   2163 	/* Honor $TMPDIR if it is valid, strip a trailing '/'. */
   2164 	tmpdir = Var_Subst("${TMPDIR:tA:U" _PATH_TMP ":S,/$,,W}/",
   2165 	    SCOPE_GLOBAL, VARE_EVAL);
   2166 	/* TODO: handle errors */
   2167 
   2168 	if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
   2169 		free(tmpdir);
   2170 		tmpdir = bmake_strdup(_PATH_TMP);
   2171 	}
   2172 	return tmpdir;
   2173 }
   2174 
   2175 /*
   2176  * Create and open a temp file using "pattern".
   2177  * If tfile is provided, set it to a copy of the filename created.
   2178  * Otherwise unlink the file once open.
   2179  */
   2180 int
   2181 mkTempFile(const char *pattern, char *tfile, size_t tfile_sz)
   2182 {
   2183 	static char *tmpdir = NULL;
   2184 	char tbuf[MAXPATHLEN];
   2185 	int fd;
   2186 
   2187 	if (pattern == NULL)
   2188 		pattern = "makeXXXXXX";
   2189 	if (tmpdir == NULL)
   2190 		tmpdir = getTmpdir();
   2191 	if (tfile == NULL) {
   2192 		tfile = tbuf;
   2193 		tfile_sz = sizeof tbuf;
   2194 	}
   2195 
   2196 	if (pattern[0] == '/')
   2197 		snprintf(tfile, tfile_sz, "%s", pattern);
   2198 	else
   2199 		snprintf(tfile, tfile_sz, "%s%s", tmpdir, pattern);
   2200 
   2201 	if ((fd = mkstemp(tfile)) < 0)
   2202 		Punt("Could not create temporary file %s: %s", tfile,
   2203 		    strerror(errno));
   2204 	if (tfile == tbuf)
   2205 		unlink(tfile);	/* we just want the descriptor */
   2206 
   2207 	return fd;
   2208 }
   2209 
   2210 /*
   2211  * Convert a string representation of a boolean into a boolean value.
   2212  * Anything that looks like "No", "False", "Off", "0" etc. is false,
   2213  * the empty string is the fallback, everything else is true.
   2214  */
   2215 bool
   2216 ParseBoolean(const char *s, bool fallback)
   2217 {
   2218 	char ch = ch_tolower(s[0]);
   2219 	if (ch == '\0')
   2220 		return fallback;
   2221 	if (ch == '0' || ch == 'f' || ch == 'n')
   2222 		return false;
   2223 	if (ch == 'o')
   2224 		return ch_tolower(s[1]) != 'f';
   2225 	return true;
   2226 }
   2227