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