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