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