Home | History | Annotate | Line # | Download | only in make
main.c revision 1.420
      1 /*	$NetBSD: main.c,v 1.420 2020/10/31 21:09:22 sjg 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.420 2020/10/31 21:09:22 sjg 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			oldVars;	/* variable substitution style */
    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 
    160 extern SearchPath *parseIncPath;
    161 
    162 /*
    163  * For compatibility with the POSIX version of MAKEFLAGS that includes
    164  * all the options with out -, convert flags to -f -l -a -g -s.
    165  */
    166 static char *
    167 explode(const char *flags)
    168 {
    169     size_t len;
    170     char *nf, *st;
    171     const char *f;
    172 
    173     if (flags == NULL)
    174 	return NULL;
    175 
    176     for (f = flags; *f; f++)
    177 	if (!ch_isalpha(*f))
    178 	    break;
    179 
    180     if (*f)
    181 	return bmake_strdup(flags);
    182 
    183     len = strlen(flags);
    184     st = nf = bmake_malloc(len * 3 + 1);
    185     while (*flags) {
    186 	*nf++ = '-';
    187 	*nf++ = *flags++;
    188 	*nf++ = ' ';
    189     }
    190     *nf = '\0';
    191     return st;
    192 }
    193 
    194 static void
    195 parse_debug_option_F(const char *modules)
    196 {
    197     const char *mode;
    198     size_t len;
    199     char *fname;
    200 
    201     if (opts.debug_file != stdout && opts.debug_file != stderr)
    202 	fclose(opts.debug_file);
    203 
    204     if (*modules == '+') {
    205 	modules++;
    206 	mode = "a";
    207     } else
    208 	mode = "w";
    209 
    210     if (strcmp(modules, "stdout") == 0) {
    211 	opts.debug_file = stdout;
    212 	return;
    213     }
    214     if (strcmp(modules, "stderr") == 0) {
    215 	opts.debug_file = stderr;
    216 	return;
    217     }
    218 
    219     len = strlen(modules);
    220     fname = bmake_malloc(len + 20);
    221     memcpy(fname, modules, len + 1);
    222 
    223     /* Let the filename be modified by the pid */
    224     if (strcmp(fname + len - 3, ".%d") == 0)
    225 	snprintf(fname + len - 2, 20, "%d", getpid());
    226 
    227     opts.debug_file = fopen(fname, mode);
    228     if (!opts.debug_file) {
    229 	fprintf(stderr, "Cannot open debug file %s\n",
    230 		fname);
    231 	usage();
    232     }
    233     free(fname);
    234 }
    235 
    236 static void
    237 parse_debug_options(const char *argvalue)
    238 {
    239 	const char *modules;
    240 
    241 	for (modules = argvalue; *modules; ++modules) {
    242 		switch (*modules) {
    243 		case '0':	/* undocumented, only intended for tests */
    244 			opts.debug &= DEBUG_LINT;
    245 			break;
    246 		case 'A':
    247 			opts.debug = ~(0|DEBUG_LINT);
    248 			break;
    249 		case 'a':
    250 			opts.debug |= DEBUG_ARCH;
    251 			break;
    252 		case 'C':
    253 			opts.debug |= DEBUG_CWD;
    254 			break;
    255 		case 'c':
    256 			opts.debug |= DEBUG_COND;
    257 			break;
    258 		case 'd':
    259 			opts.debug |= DEBUG_DIR;
    260 			break;
    261 		case 'e':
    262 			opts.debug |= DEBUG_ERROR;
    263 			break;
    264 		case 'f':
    265 			opts.debug |= DEBUG_FOR;
    266 			break;
    267 		case 'g':
    268 			if (modules[1] == '1') {
    269 				opts.debug |= DEBUG_GRAPH1;
    270 				++modules;
    271 			}
    272 			else if (modules[1] == '2') {
    273 				opts.debug |= DEBUG_GRAPH2;
    274 				++modules;
    275 			}
    276 			else if (modules[1] == '3') {
    277 				opts.debug |= DEBUG_GRAPH3;
    278 				++modules;
    279 			}
    280 			break;
    281 		case 'h':
    282 			opts.debug |= DEBUG_HASH;
    283 			break;
    284 		case 'j':
    285 			opts.debug |= DEBUG_JOB;
    286 			break;
    287 		case 'L':
    288 			opts.debug |= DEBUG_LINT;
    289 			break;
    290 		case 'l':
    291 			opts.debug |= DEBUG_LOUD;
    292 			break;
    293 		case 'M':
    294 			opts.debug |= DEBUG_META;
    295 			break;
    296 		case 'm':
    297 			opts.debug |= DEBUG_MAKE;
    298 			break;
    299 		case 'n':
    300 			opts.debug |= DEBUG_SCRIPT;
    301 			break;
    302 		case 'p':
    303 			opts.debug |= DEBUG_PARSE;
    304 			break;
    305 		case 's':
    306 			opts.debug |= DEBUG_SUFF;
    307 			break;
    308 		case 't':
    309 			opts.debug |= DEBUG_TARG;
    310 			break;
    311 		case 'V':
    312 			opts.debugVflag = TRUE;
    313 			break;
    314 		case 'v':
    315 			opts.debug |= DEBUG_VAR;
    316 			break;
    317 		case 'x':
    318 			opts.debug |= DEBUG_SHELL;
    319 			break;
    320 		case 'F':
    321 			parse_debug_option_F(modules + 1);
    322 			goto debug_setbuf;
    323 		default:
    324 			(void)fprintf(stderr,
    325 			    "%s: illegal argument to d option -- %c\n",
    326 			    progname, *modules);
    327 			usage();
    328 		}
    329 	}
    330 debug_setbuf:
    331 	/*
    332 	 * Make the debug_file unbuffered, and make
    333 	 * stdout line buffered (unless debugfile == stdout).
    334 	 */
    335 	setvbuf(opts.debug_file, NULL, _IONBF, 0);
    336 	if (opts.debug_file != stdout) {
    337 		setvbuf(stdout, NULL, _IOLBF, 0);
    338 	}
    339 }
    340 
    341 /*
    342  * does path contain any relative components
    343  */
    344 static Boolean
    345 is_relpath(const char *path)
    346 {
    347 	const char *cp;
    348 
    349 	if (path[0] != '/')
    350 		return TRUE;
    351 	cp = path;
    352 	while ((cp = strstr(cp, "/.")) != NULL) {
    353 		cp += 2;
    354 		if (cp[0] == '/' || cp[0] == '\0')
    355 			return TRUE;
    356 		else if (cp[0] == '.') {
    357 			if (cp[1] == '/' || cp[1] == '\0')
    358 				return TRUE;
    359 		}
    360 	}
    361 	return FALSE;
    362 }
    363 
    364 static void
    365 MainParseArgChdir(const char *argvalue)
    366 {
    367 	struct stat sa, sb;
    368 
    369 	if (chdir(argvalue) == -1) {
    370 		(void)fprintf(stderr, "%s: chdir %s: %s\n",
    371 		    progname, argvalue, strerror(errno));
    372 		exit(1);
    373 	}
    374 	if (getcwd(curdir, MAXPATHLEN) == NULL) {
    375 		(void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
    376 		exit(2);
    377 	}
    378 	if (!is_relpath(argvalue) &&
    379 	    stat(argvalue, &sa) != -1 &&
    380 	    stat(curdir, &sb) != -1 &&
    381 	    sa.st_ino == sb.st_ino &&
    382 	    sa.st_dev == sb.st_dev)
    383 		strncpy(curdir, argvalue, MAXPATHLEN);
    384 	ignorePWD = TRUE;
    385 }
    386 
    387 static void
    388 MainParseArgJobsInternal(const char *argvalue)
    389 {
    390 	if (sscanf(argvalue, "%d,%d", &jp_0, &jp_1) != 2) {
    391 		(void)fprintf(stderr,
    392 			      "%s: internal error -- J option malformed (%s)\n",
    393 			      progname, argvalue);
    394 		usage();
    395 	}
    396 	if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
    397 	    (fcntl(jp_1, F_GETFD, 0) < 0)) {
    398 #if 0
    399 		(void)fprintf(stderr,
    400 		    "%s: ###### warning -- J descriptors were closed!\n",
    401 		    progname);
    402 		exit(2);
    403 #endif
    404 		jp_0 = -1;
    405 		jp_1 = -1;
    406 		opts.compatMake = TRUE;
    407 	} else {
    408 		Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
    409 		Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    410 	}
    411 }
    412 
    413 static void
    414 MainParseArgJobs(const char *argvalue)
    415 {
    416 	char *p;
    417 
    418 	forceJobs = TRUE;
    419 	opts.maxJobs = (int)strtol(argvalue, &p, 0);
    420 	if (*p != '\0' || opts.maxJobs < 1) {
    421 		(void)fprintf(stderr,
    422 		    "%s: illegal argument to -j -- must be positive integer!\n",
    423 		    progname);
    424 		exit(1);	/* XXX: why not 2? */
    425 	}
    426 	Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
    427 	Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    428 	Var_Set(".MAKE.JOBS", argvalue, VAR_GLOBAL);
    429 	maxJobTokens = opts.maxJobs;
    430 }
    431 
    432 static void
    433 MainParseArgSysInc(const char *argvalue)
    434 {
    435 	/* look for magic parent directory search string */
    436 	if (strncmp(".../", argvalue, 4) == 0) {
    437 		char *found_path = Dir_FindHereOrAbove(curdir, argvalue + 4);
    438 		if (found_path == NULL)
    439 			return;
    440 		(void)Dir_AddDir(sysIncPath, found_path);
    441 		free(found_path);
    442 	} else {
    443 		(void)Dir_AddDir(sysIncPath, argvalue);
    444 	}
    445 	Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
    446 	Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    447 }
    448 
    449 static Boolean
    450 MainParseArg(char c, const char *argvalue)
    451 {
    452 	switch (c) {
    453 	case '\0':
    454 		break;
    455 	case 'B':
    456 		opts.compatMake = TRUE;
    457 		Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
    458 		Var_Set(MAKE_MODE, "compat", VAR_GLOBAL);
    459 		break;
    460 	case 'C':
    461 		MainParseArgChdir(argvalue);
    462 		break;
    463 	case 'D':
    464 		if (argvalue[0] == '\0') return FALSE;
    465 		Var_Set(argvalue, "1", VAR_GLOBAL);
    466 		Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
    467 		Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    468 		break;
    469 	case 'I':
    470 		Parse_AddIncludeDir(argvalue);
    471 		Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
    472 		Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    473 		break;
    474 	case 'J':
    475 		MainParseArgJobsInternal(argvalue);
    476 		break;
    477 	case 'N':
    478 		opts.noExecute = TRUE;
    479 		opts.noRecursiveExecute = TRUE;
    480 		Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
    481 		break;
    482 	case 'S':
    483 		opts.keepgoing = FALSE;
    484 		Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
    485 		break;
    486 	case 'T':
    487 		tracefile = bmake_strdup(argvalue);
    488 		Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
    489 		Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    490 		break;
    491 	case 'V':
    492 	case 'v':
    493 		opts.printVars = c == 'v' ? EXPAND_VARS : COMPAT_VARS;
    494 		Lst_Append(opts.variables, bmake_strdup(argvalue));
    495 		/* XXX: Why always -V? */
    496 		Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
    497 		Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    498 		break;
    499 	case 'W':
    500 		opts.parseWarnFatal = TRUE;
    501 		break;
    502 	case 'X':
    503 		opts.varNoExportEnv = TRUE;
    504 		Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
    505 		break;
    506 	case 'd':
    507 		/* If '-d-opts' don't pass to children */
    508 		if (argvalue[0] == '-')
    509 			argvalue++;
    510 		else {
    511 			Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
    512 			Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    513 		}
    514 		parse_debug_options(argvalue);
    515 		break;
    516 	case 'e':
    517 		opts.checkEnvFirst = TRUE;
    518 		Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
    519 		break;
    520 	case 'f':
    521 		Lst_Append(opts.makefiles, bmake_strdup(argvalue));
    522 		break;
    523 	case 'i':
    524 		opts.ignoreErrors = TRUE;
    525 		Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
    526 		break;
    527 	case 'j':
    528 		MainParseArgJobs(argvalue);
    529 		break;
    530 	case 'k':
    531 		opts.keepgoing = TRUE;
    532 		Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
    533 		break;
    534 	case 'm':
    535 		MainParseArgSysInc(argvalue);
    536 		break;
    537 	case 'n':
    538 		opts.noExecute = TRUE;
    539 		Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
    540 		break;
    541 	case 'q':
    542 		opts.queryFlag = TRUE;
    543 		/* Kind of nonsensical, wot? */
    544 		Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
    545 		break;
    546 	case 'r':
    547 		opts.noBuiltins = TRUE;
    548 		Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
    549 		break;
    550 	case 's':
    551 		opts.beSilent = TRUE;
    552 		Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
    553 		break;
    554 	case 't':
    555 		opts.touchFlag = TRUE;
    556 		Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
    557 		break;
    558 	case 'w':
    559 		opts.enterFlag = TRUE;
    560 		Var_Append(MAKEFLAGS, "-w", VAR_GLOBAL);
    561 		break;
    562 	default:
    563 	case '?':
    564 		usage();
    565 	}
    566 	return TRUE;
    567 }
    568 
    569 /* Parse the given arguments.  Called from main() and from
    570  * Main_ParseArgLine() when the .MAKEFLAGS target is used.
    571  *
    572  * The arguments must be treated as read-only and will be freed after the
    573  * call.
    574  *
    575  * XXX: Deal with command line overriding .MAKEFLAGS in makefile */
    576 static void
    577 MainParseArgs(int argc, char **argv)
    578 {
    579 	char c;
    580 	int arginc;
    581 	char *argvalue;
    582 	char *optscan;
    583 	Boolean inOption, dashDash = FALSE;
    584 
    585 	const char *optspecs = "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrstv:w";
    586 /* Can't actually use getopt(3) because rescanning is not portable */
    587 
    588 rearg:
    589 	inOption = FALSE;
    590 	optscan = NULL;
    591 	while (argc > 1) {
    592 		const char *optspec;
    593 		if (!inOption)
    594 			optscan = argv[1];
    595 		c = *optscan++;
    596 		arginc = 0;
    597 		if (inOption) {
    598 			if (c == '\0') {
    599 				++argv;
    600 				--argc;
    601 				inOption = FALSE;
    602 				continue;
    603 			}
    604 		} else {
    605 			if (c != '-' || dashDash)
    606 				break;
    607 			inOption = TRUE;
    608 			c = *optscan++;
    609 		}
    610 		/* '-' found at some earlier point */
    611 		optspec = strchr(optspecs, c);
    612 		if (c != '\0' && optspec != NULL && optspec[1] == ':') {
    613 			/* -<something> found, and <something> should have an arg */
    614 			inOption = FALSE;
    615 			arginc = 1;
    616 			argvalue = optscan;
    617 			if (*argvalue == '\0') {
    618 				if (argc < 3)
    619 					goto noarg;
    620 				argvalue = argv[2];
    621 				arginc = 2;
    622 			}
    623 		} else {
    624 			argvalue = NULL;
    625 		}
    626 		switch (c) {
    627 		case '\0':
    628 			arginc = 1;
    629 			inOption = FALSE;
    630 			break;
    631 		case '-':
    632 			dashDash = TRUE;
    633 			break;
    634 		default:
    635 			if (!MainParseArg(c, argvalue))
    636 				goto noarg;
    637 		}
    638 		argv += arginc;
    639 		argc -= arginc;
    640 	}
    641 
    642 	oldVars = TRUE;
    643 
    644 	/*
    645 	 * See if the rest of the arguments are variable assignments and
    646 	 * perform them if so. Else take them to be targets and stuff them
    647 	 * on the end of the "create" list.
    648 	 */
    649 	for (; argc > 1; ++argv, --argc) {
    650 		VarAssign var;
    651 		if (Parse_IsVar(argv[1], &var)) {
    652 			Parse_DoVar(&var, VAR_CMDLINE);
    653 		} else {
    654 			if (!*argv[1])
    655 				Punt("illegal (null) argument.");
    656 			if (*argv[1] == '-' && !dashDash)
    657 				goto rearg;
    658 			Lst_Append(opts.create, bmake_strdup(argv[1]));
    659 		}
    660 	}
    661 
    662 	return;
    663 noarg:
    664 	(void)fprintf(stderr, "%s: option requires an argument -- %c\n",
    665 	    progname, c);
    666 	usage();
    667 }
    668 
    669 /* Break a line of arguments into words and parse them.
    670  *
    671  * Used when a .MFLAGS or .MAKEFLAGS target is encountered during parsing and
    672  * by main() when reading the MAKEFLAGS environment variable. */
    673 void
    674 Main_ParseArgLine(const char *line)
    675 {
    676 	Words words;
    677 	void *p1;
    678 	const char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
    679 	char *buf;
    680 
    681 	if (line == NULL)
    682 		return;
    683 	for (; *line == ' '; ++line)
    684 		continue;
    685 	if (!*line)
    686 		return;
    687 
    688 	buf = str_concat3(argv0, " ", line);
    689 	free(p1);
    690 
    691 	words = Str_Words(buf, TRUE);
    692 	if (words.words == NULL) {
    693 		Error("Unterminated quoted string [%s]", buf);
    694 		free(buf);
    695 		return;
    696 	}
    697 	free(buf);
    698 	MainParseArgs((int)words.len, words.words);
    699 
    700 	Words_Free(words);
    701 }
    702 
    703 Boolean
    704 Main_SetObjdir(const char *fmt, ...)
    705 {
    706 	struct stat sb;
    707 	char *path;
    708 	char buf[MAXPATHLEN + 1];
    709 	char buf2[MAXPATHLEN + 1];
    710 	Boolean rc = FALSE;
    711 	va_list ap;
    712 
    713 	va_start(ap, fmt);
    714 	vsnprintf(path = buf, MAXPATHLEN, fmt, ap);
    715 	va_end(ap);
    716 
    717 	if (path[0] != '/') {
    718 		snprintf(buf2, MAXPATHLEN, "%s/%s", curdir, path);
    719 		path = buf2;
    720 	}
    721 
    722 	/* look for the directory and try to chdir there */
    723 	if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
    724 		/* if not .CURDIR it must be writable */
    725 		if ((strcmp(path, curdir) != 0 && access(path, W_OK) != 0) ||
    726 		    chdir(path)) {
    727 			(void)fprintf(stderr, "make warning: %s: %s.\n",
    728 				      path, strerror(errno));
    729 		} else {
    730 			snprintf(objdir, sizeof objdir, "%s", path);
    731 			Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
    732 			setenv("PWD", objdir, 1);
    733 			Dir_InitDot();
    734 			purge_cached_realpaths();
    735 			rc = TRUE;
    736 			if (opts.enterFlag && strcmp(objdir, curdir) != 0)
    737 				enterFlagObj = TRUE;
    738 		}
    739 	}
    740 
    741 	return rc;
    742 }
    743 
    744 static Boolean
    745 Main_SetVarObjdir(const char *var, const char *suffix)
    746 {
    747 	void *path_freeIt;
    748 	const char *path = Var_Value(var, VAR_CMDLINE, &path_freeIt);
    749 	const char *xpath;
    750 	char *xpath_freeIt;
    751 
    752 	if (path == NULL || path[0] == '\0') {
    753 		bmake_free(path_freeIt);
    754 		return FALSE;
    755 	}
    756 
    757 	/* expand variable substitutions */
    758 	xpath = path;
    759 	xpath_freeIt = NULL;
    760 	if (strchr(path, '$') != 0) {
    761 		(void)Var_Subst(path, VAR_GLOBAL, VARE_WANTRES, &xpath_freeIt);
    762 		/* TODO: handle errors */
    763 		xpath = xpath_freeIt;
    764 	}
    765 
    766 	(void)Main_SetObjdir("%s%s", xpath, suffix);
    767 
    768 	bmake_free(xpath_freeIt);
    769 	bmake_free(path_freeIt);
    770 	return TRUE;
    771 }
    772 
    773 /* Read and parse the makefile.
    774  * Return TRUE if reading the makefile succeeded. */
    775 static int
    776 ReadMakefileSucceeded(void *fname, void *unused)
    777 {
    778 	return ReadMakefile(fname) == 0;
    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)
    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 static void
    870 doPrintVars(void)
    871 {
    872 	StringListNode *ln;
    873 	Boolean expandVars;
    874 
    875 	if (opts.printVars == EXPAND_VARS)
    876 		expandVars = TRUE;
    877 	else if (opts.debugVflag)
    878 		expandVars = FALSE;
    879 	else
    880 		expandVars = getBoolean(".MAKE.EXPAND_VARIABLES", FALSE);
    881 
    882 	for (ln = opts.variables->first; ln != NULL; ln = ln->next) {
    883 		const char *varname = ln->datum;
    884 		PrintVar(varname, expandVars);
    885 	}
    886 }
    887 
    888 static Boolean
    889 runTargets(void)
    890 {
    891 	GNodeList *targs; /* target nodes to create -- passed to Make_Init */
    892 	Boolean outOfDate;	/* FALSE if all targets up to date */
    893 
    894 	/*
    895 	 * Have now read the entire graph and need to make a list of
    896 	 * targets to create. If none was given on the command line,
    897 	 * we consult the parsing module to find the main target(s)
    898 	 * to create.
    899 	 */
    900 	if (Lst_IsEmpty(opts.create))
    901 		targs = Parse_MainName();
    902 	else
    903 		targs = Targ_FindList(opts.create);
    904 
    905 	if (!opts.compatMake) {
    906 		/*
    907 		 * Initialize job module before traversing the graph
    908 		 * now that any .BEGIN and .END targets have been read.
    909 		 * This is done only if the -q flag wasn't given
    910 		 * (to prevent the .BEGIN from being executed should
    911 		 * it exist).
    912 		 */
    913 		if (!opts.queryFlag) {
    914 			Job_Init();
    915 			jobsRunning = TRUE;
    916 		}
    917 
    918 		/* Traverse the graph, checking on all the targets */
    919 		outOfDate = Make_Run(targs);
    920 	} else {
    921 		/*
    922 		 * Compat_Init will take care of creating all the
    923 		 * targets as well as initializing the module.
    924 		 */
    925 		Compat_Run(targs);
    926 		outOfDate = FALSE;
    927 	}
    928 	Lst_Free(targs);
    929 	return outOfDate;
    930 }
    931 
    932 /*
    933  * Set up the .TARGETS variable to contain the list of targets to be
    934  * created. If none specified, make the variable empty -- the parser
    935  * will fill the thing in with the default or .MAIN target.
    936  */
    937 static void
    938 InitVarTargets(void)
    939 {
    940 	StringListNode *ln;
    941 
    942 	if (Lst_IsEmpty(opts.create)) {
    943 		Var_Set(".TARGETS", "", VAR_GLOBAL);
    944 		return;
    945 	}
    946 
    947 	for (ln = opts.create->first; ln != NULL; ln = ln->next) {
    948 		char *name = ln->datum;
    949 		Var_Append(".TARGETS", name, VAR_GLOBAL);
    950 	}
    951 }
    952 
    953 static void
    954 InitRandom(void)
    955 {
    956 	struct timeval tv;
    957 
    958 	gettimeofday(&tv, NULL);
    959 	srandom((unsigned int)(tv.tv_sec + tv.tv_usec));
    960 }
    961 
    962 static const char *
    963 init_machine(const struct utsname *utsname)
    964 {
    965 	const char *machine = getenv("MACHINE");
    966 	if (machine != NULL)
    967 		return machine;
    968 
    969 #ifdef MAKE_NATIVE
    970 	return utsname->machine;
    971 #else
    972 #ifdef MAKE_MACHINE
    973 	return MAKE_MACHINE;
    974 #else
    975 	return "unknown";
    976 #endif
    977 #endif
    978 }
    979 
    980 static const char *
    981 init_machine_arch(void)
    982 {
    983 	const char *env = getenv("MACHINE_ARCH");
    984 	if (env != NULL)
    985 		return env;
    986 
    987 #ifdef MAKE_NATIVE
    988 	{
    989 		struct utsname utsname;
    990 		static char machine_arch_buf[sizeof(utsname.machine)];
    991 		const int mib[2] = { CTL_HW, HW_MACHINE_ARCH };
    992 		size_t len = sizeof(machine_arch_buf);
    993 
    994 		if (sysctl(mib, __arraycount(mib), machine_arch_buf,
    995 			&len, NULL, 0) < 0) {
    996 		    (void)fprintf(stderr, "%s: sysctl failed (%s).\n", progname,
    997 			strerror(errno));
    998 		    exit(2);
    999 		}
   1000 
   1001 		return machine_arch_buf;
   1002 	}
   1003 #else
   1004 #ifndef MACHINE_ARCH
   1005 #ifdef MAKE_MACHINE_ARCH
   1006 	return MAKE_MACHINE_ARCH;
   1007 #else
   1008 	return "unknown";
   1009 #endif
   1010 #else
   1011 	return MACHINE_ARCH;
   1012 #endif
   1013 #endif
   1014 }
   1015 
   1016 #ifndef NO_PWD_OVERRIDE
   1017 /*
   1018  * All this code is so that we know where we are when we start up
   1019  * on a different machine with pmake.
   1020  *
   1021  * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
   1022  * since the value of curdir can vary depending on how we got
   1023  * here.  Ie sitting at a shell prompt (shell that provides $PWD)
   1024  * or via subdir.mk in which case its likely a shell which does
   1025  * not provide it.
   1026  *
   1027  * So, to stop it breaking this case only, we ignore PWD if
   1028  * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a variable expression.
   1029  */
   1030 static void
   1031 HandlePWD(const struct stat *curdir_st)
   1032 {
   1033 	char *pwd;
   1034 	void *prefix_freeIt, *makeobjdir_freeIt;
   1035 	const char *makeobjdir;
   1036 	struct stat pwd_st;
   1037 
   1038 	if (ignorePWD || (pwd = getenv("PWD")) == NULL)
   1039 		return;
   1040 
   1041 	if (Var_Value("MAKEOBJDIRPREFIX", VAR_CMDLINE, &prefix_freeIt) != NULL) {
   1042 		bmake_free(prefix_freeIt);
   1043 		return;
   1044 	}
   1045 
   1046 	makeobjdir = Var_Value("MAKEOBJDIR", VAR_CMDLINE, &makeobjdir_freeIt);
   1047 	if (makeobjdir != NULL && strchr(makeobjdir, '$') != NULL)
   1048 		goto ignore_pwd;
   1049 
   1050 	if (stat(pwd, &pwd_st) == 0 &&
   1051 	    curdir_st->st_ino == pwd_st.st_ino &&
   1052 	    curdir_st->st_dev == pwd_st.st_dev)
   1053 		(void)strncpy(curdir, pwd, MAXPATHLEN);
   1054 
   1055 ignore_pwd:
   1056 	bmake_free(makeobjdir_freeIt);
   1057 }
   1058 #endif
   1059 
   1060 /*
   1061  * Find the .OBJDIR.  If MAKEOBJDIRPREFIX, or failing that,
   1062  * MAKEOBJDIR is set in the environment, try only that value
   1063  * and fall back to .CURDIR if it does not exist.
   1064  *
   1065  * Otherwise, try _PATH_OBJDIR.MACHINE-MACHINE_ARCH, _PATH_OBJDIR.MACHINE,
   1066  * and * finally _PATH_OBJDIRPREFIX`pwd`, in that order.  If none
   1067  * of these paths exist, just use .CURDIR.
   1068  */
   1069 static void
   1070 InitObjdir(const char *machine, const char *machine_arch)
   1071 {
   1072 	Dir_InitDir(curdir);
   1073 	(void)Main_SetObjdir("%s", curdir);
   1074 
   1075 	if (!Main_SetVarObjdir("MAKEOBJDIRPREFIX", curdir) &&
   1076 	    !Main_SetVarObjdir("MAKEOBJDIR", "") &&
   1077 	    !Main_SetObjdir("%s.%s-%s", _PATH_OBJDIR, machine, machine_arch) &&
   1078 	    !Main_SetObjdir("%s.%s", _PATH_OBJDIR, machine) &&
   1079 	    !Main_SetObjdir("%s", _PATH_OBJDIR))
   1080 		(void)Main_SetObjdir("%s%s", _PATH_OBJDIRPREFIX, curdir);
   1081 }
   1082 
   1083 /* get rid of resource limit on file descriptors */
   1084 static void
   1085 UnlimitFiles(void)
   1086 {
   1087 #if defined(MAKE_NATIVE) || (defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE))
   1088 	struct rlimit rl;
   1089 	if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
   1090 	    rl.rlim_cur != rl.rlim_max) {
   1091 		rl.rlim_cur = rl.rlim_max;
   1092 		(void)setrlimit(RLIMIT_NOFILE, &rl);
   1093 	}
   1094 #endif
   1095 }
   1096 
   1097 static void
   1098 CmdOpts_Init(void)
   1099 {
   1100 	opts.compatMake = FALSE;	/* No compat mode */
   1101 	opts.debug = 0;			/* No debug verbosity, please. */
   1102 	/* opts.debug_file has been initialized earlier */
   1103 	opts.debugVflag = FALSE;
   1104 	opts.checkEnvFirst = FALSE;
   1105 	opts.makefiles = Lst_New();
   1106 	opts.ignoreErrors = FALSE;	/* Pay attention to non-zero returns */
   1107 	opts.maxJobs = DEFMAXLOCAL;	/* Set default local max concurrency */
   1108 	opts.keepgoing = FALSE;		/* Stop on error */
   1109 	opts.noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
   1110 	opts.noExecute = FALSE;		/* Execute all commands */
   1111 	opts.queryFlag = FALSE;		/* This is not just a check-run */
   1112 	opts.noBuiltins = FALSE;	/* Read the built-in rules */
   1113 	opts.beSilent = FALSE;		/* Print commands as executed */
   1114 	opts.touchFlag = FALSE;		/* Actually update targets */
   1115 	opts.printVars = 0;
   1116 	opts.variables = Lst_New();
   1117 	opts.parseWarnFatal = FALSE;
   1118 	opts.enterFlag = FALSE;
   1119 	opts.varNoExportEnv = FALSE;
   1120 	opts.create = Lst_New();
   1121 }
   1122 
   1123 /* Initialize MAKE and .MAKE to the path of the executable, so that it can be
   1124  * found by execvp(3) and the shells, even after a chdir.
   1125  *
   1126  * If it's a relative path and contains a '/', resolve it to an absolute path.
   1127  * Otherwise keep it as is, assuming it will be found in the PATH. */
   1128 static void
   1129 InitVarMake(const char *argv0)
   1130 {
   1131 	const char *make = argv0;
   1132 
   1133 	if (argv0[0] != '/' && strchr(argv0, '/') != NULL) {
   1134 		char pathbuf[MAXPATHLEN];
   1135 		const char *abs = cached_realpath(argv0, pathbuf);
   1136 		struct stat st;
   1137 		if (abs != NULL && abs[0] == '/' && stat(make, &st) == 0)
   1138 			make = abs;
   1139 	}
   1140 
   1141 	Var_Set("MAKE", make, VAR_GLOBAL);
   1142 	Var_Set(".MAKE", make, VAR_GLOBAL);
   1143 }
   1144 
   1145 static void
   1146 InitDefSysIncPath(char *syspath)
   1147 {
   1148 	static char defsyspath[] = _PATH_DEFSYSPATH;
   1149 	char *start, *cp;
   1150 
   1151 	/*
   1152 	 * If no user-supplied system path was given (through the -m option)
   1153 	 * add the directories from the DEFSYSPATH (more than one may be given
   1154 	 * as dir1:...:dirn) to the system include path.
   1155 	 */
   1156 	/* XXX: mismatch: the -m option sets sysIncPath, not syspath */
   1157 	if (syspath == NULL || syspath[0] == '\0')
   1158 		syspath = defsyspath;
   1159 	else
   1160 		syspath = bmake_strdup(syspath);
   1161 
   1162 	for (start = syspath; *start != '\0'; start = cp) {
   1163 		for (cp = start; *cp != '\0' && *cp != ':'; cp++)
   1164 			continue;
   1165 		if (*cp == ':') {
   1166 			*cp++ = '\0';
   1167 		}
   1168 		/* look for magic parent directory search string */
   1169 		if (strncmp(".../", start, 4) != 0) {
   1170 			(void)Dir_AddDir(defSysIncPath, start);
   1171 		} else {
   1172 			char *dir = Dir_FindHereOrAbove(curdir, start + 4);
   1173 			if (dir != NULL) {
   1174 				(void)Dir_AddDir(defSysIncPath, dir);
   1175 				free(dir);
   1176 			}
   1177 		}
   1178 	}
   1179 
   1180 	if (syspath != defsyspath)
   1181 		free(syspath);
   1182 }
   1183 
   1184 static void
   1185 ReadBuiltinRules(void)
   1186 {
   1187 	StringList *sysMkPath = Lst_New();
   1188 	Dir_Expand(_PATH_DEFSYSMK,
   1189 		   Lst_IsEmpty(sysIncPath) ? defSysIncPath : sysIncPath,
   1190 		   sysMkPath);
   1191 	if (Lst_IsEmpty(sysMkPath))
   1192 		Fatal("%s: no system rules (%s).", progname, _PATH_DEFSYSMK);
   1193 	if (!Lst_ForEachUntil(sysMkPath, ReadMakefileSucceeded, NULL))
   1194 		Fatal("%s: cannot open %s.", progname,
   1195 		      (char *)sysMkPath->first->datum);
   1196 	/* XXX: sysMkPath is not freed */
   1197 }
   1198 
   1199 static void
   1200 InitMaxJobs(void)
   1201 {
   1202 	char *value;
   1203 	int n;
   1204 
   1205 	if (forceJobs || opts.compatMake ||
   1206 	    !Var_Exists(".MAKE.JOBS", VAR_GLOBAL))
   1207 		return;
   1208 
   1209 	(void)Var_Subst("${.MAKE.JOBS}", VAR_GLOBAL, VARE_WANTRES, &value);
   1210 	/* TODO: handle errors */
   1211 	n = (int)strtol(value, NULL, 0);
   1212 	if (n < 1) {
   1213 		(void)fprintf(stderr,
   1214 			      "%s: illegal value for .MAKE.JOBS "
   1215 			      "-- must be positive integer!\n",
   1216 			      progname);
   1217 		exit(1);
   1218 	}
   1219 
   1220 	if (n != opts.maxJobs) {
   1221 		Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
   1222 		Var_Append(MAKEFLAGS, value, VAR_GLOBAL);
   1223 	}
   1224 
   1225 	opts.maxJobs = n;
   1226 	maxJobTokens = opts.maxJobs;
   1227 	forceJobs = TRUE;
   1228 	free(value);
   1229 }
   1230 
   1231 /*
   1232  * For compatibility, look at the directories in the VPATH variable
   1233  * and add them to the search path, if the variable is defined. The
   1234  * variable's value is in the same format as the PATH environment
   1235  * variable, i.e. <directory>:<directory>:<directory>...
   1236  */
   1237 static void
   1238 InitVpath(void)
   1239 {
   1240 	char *vpath, savec, *path;
   1241 	if (!Var_Exists("VPATH", VAR_CMDLINE))
   1242 		return;
   1243 
   1244 	(void)Var_Subst("${VPATH}", VAR_CMDLINE, VARE_WANTRES, &vpath);
   1245 	/* TODO: handle errors */
   1246 	path = vpath;
   1247 	do {
   1248 		char *cp;
   1249 		/* skip to end of directory */
   1250 		for (cp = path; *cp != ':' && *cp != '\0'; cp++)
   1251 			continue;
   1252 		/* Save terminator character so know when to stop */
   1253 		savec = *cp;
   1254 		*cp = '\0';
   1255 		/* Add directory to search path */
   1256 		(void)Dir_AddDir(dirSearchPath, path);
   1257 		*cp = savec;
   1258 		path = cp + 1;
   1259 	} while (savec == ':');
   1260 	free(vpath);
   1261 }
   1262 
   1263 static void
   1264 ReadMakefiles(void)
   1265 {
   1266 	if (opts.makefiles->first != NULL) {
   1267 		StringListNode *ln;
   1268 
   1269 		for (ln = opts.makefiles->first; ln != NULL; ln = ln->next) {
   1270 			if (ReadMakefile(ln->datum) != 0)
   1271 				Fatal("%s: cannot open %s.",
   1272 				      progname, (char *)ln->datum);
   1273 		}
   1274 	} else {
   1275 		char *p1;
   1276 		(void)Var_Subst("${" MAKEFILE_PREFERENCE "}",
   1277 				VAR_CMDLINE, VARE_WANTRES, &p1);
   1278 		/* TODO: handle errors */
   1279 		(void)str2Lst_Append(opts.makefiles, p1, NULL);
   1280 		(void)Lst_ForEachUntil(opts.makefiles,
   1281 				       ReadMakefileSucceeded, NULL);
   1282 		free(p1);
   1283 	}
   1284 }
   1285 
   1286 static void
   1287 CleanUp(void)
   1288 {
   1289 #ifdef CLEANUP
   1290 	Lst_Destroy(opts.variables, free);
   1291 	Lst_Free(opts.makefiles);	/* don't free, may be used in GNodes */
   1292 	Lst_Destroy(opts.create, free);
   1293 #endif
   1294 
   1295 	/* print the graph now it's been processed if the user requested it */
   1296 	if (DEBUG(GRAPH2))
   1297 		Targ_PrintGraph(2);
   1298 
   1299 	Trace_Log(MAKEEND, 0);
   1300 
   1301 	if (enterFlagObj)
   1302 		printf("%s: Leaving directory `%s'\n", progname, objdir);
   1303 	if (opts.enterFlag)
   1304 		printf("%s: Leaving directory `%s'\n", progname, curdir);
   1305 
   1306 #ifdef USE_META
   1307 	meta_finish();
   1308 #endif
   1309 	Suff_End();
   1310 	Targ_End();
   1311 	Arch_End();
   1312 	Var_End();
   1313 	Parse_End();
   1314 	Dir_End();
   1315 	Job_End();
   1316 	Trace_End();
   1317 }
   1318 
   1319 /*-
   1320  * main --
   1321  *	The main function, for obvious reasons. Initializes variables
   1322  *	and a few modules, then parses the arguments give it in the
   1323  *	environment and on the command line. Reads the system makefile
   1324  *	followed by either Makefile, makefile or the file given by the
   1325  *	-f argument. Sets the .MAKEFLAGS PMake variable based on all the
   1326  *	flags it has received by then uses either the Make or the Compat
   1327  *	module to create the initial list of targets.
   1328  *
   1329  * Results:
   1330  *	If -q was given, exits -1 if anything was out-of-date. Else it exits
   1331  *	0.
   1332  *
   1333  * Side Effects:
   1334  *	The program exits when done. Targets are created. etc. etc. etc.
   1335  */
   1336 int
   1337 main(int argc, char **argv)
   1338 {
   1339 	Boolean outOfDate;	/* FALSE if all targets up to date */
   1340 	struct stat sa;
   1341 	const char *machine;
   1342 	const char *machine_arch;
   1343 	char *syspath = getenv("MAKESYSPATH");
   1344 	struct utsname utsname;
   1345 
   1346 	/* default to writing debug to stderr */
   1347 	opts.debug_file = stderr;
   1348 
   1349 #ifdef SIGINFO
   1350 	(void)bmake_signal(SIGINFO, siginfo);
   1351 #endif
   1352 
   1353 	InitRandom();
   1354 
   1355 	if ((progname = strrchr(argv[0], '/')) != NULL)
   1356 		progname++;
   1357 	else
   1358 		progname = argv[0];
   1359 
   1360 	UnlimitFiles();
   1361 
   1362 	if (uname(&utsname) == -1) {
   1363 	    (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
   1364 		strerror(errno));
   1365 	    exit(2);
   1366 	}
   1367 
   1368 	/*
   1369 	 * Get the name of this type of MACHINE from utsname
   1370 	 * so we can share an executable for similar machines.
   1371 	 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
   1372 	 *
   1373 	 * Note that both MACHINE and MACHINE_ARCH are decided at
   1374 	 * run-time.
   1375 	 */
   1376 	machine = init_machine(&utsname);
   1377 	machine_arch = init_machine_arch();
   1378 
   1379 	myPid = getpid();		/* remember this for vFork() */
   1380 
   1381 	/*
   1382 	 * Just in case MAKEOBJDIR wants us to do something tricky.
   1383 	 */
   1384 	Var_Init();		/* Initialize the lists of variables for
   1385 				 * parsing arguments */
   1386 	Var_Set(".MAKE.OS", utsname.sysname, VAR_GLOBAL);
   1387 	Var_Set("MACHINE", machine, VAR_GLOBAL);
   1388 	Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
   1389 #ifdef MAKE_VERSION
   1390 	Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
   1391 #endif
   1392 	Var_Set(".newline", "\n", VAR_GLOBAL); /* handy for :@ loops */
   1393 	/*
   1394 	 * This is the traditional preference for makefiles.
   1395 	 */
   1396 #ifndef MAKEFILE_PREFERENCE_LIST
   1397 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
   1398 #endif
   1399 	Var_Set(MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST,
   1400 		VAR_GLOBAL);
   1401 	Var_Set(MAKE_DEPENDFILE, ".depend", VAR_GLOBAL);
   1402 
   1403 	CmdOpts_Init();
   1404 	allPrecious = FALSE;		/* Remove targets when interrupted */
   1405 	deleteOnError = FALSE;		/* Historical default behavior */
   1406 	jobsRunning = FALSE;
   1407 
   1408 	maxJobTokens = opts.maxJobs;
   1409 	ignorePWD = FALSE;
   1410 
   1411 	/*
   1412 	 * Initialize the parsing, directory and variable modules to prepare
   1413 	 * for the reading of inclusion paths and variable settings on the
   1414 	 * command line
   1415 	 */
   1416 
   1417 	/*
   1418 	 * Initialize various variables.
   1419 	 *	MAKE also gets this name, for compatibility
   1420 	 *	.MAKEFLAGS gets set to the empty string just in case.
   1421 	 *	MFLAGS also gets initialized empty, for compatibility.
   1422 	 */
   1423 	Parse_Init();
   1424 	InitVarMake(argv[0]);
   1425 	Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
   1426 	Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL);
   1427 	Var_Set("MFLAGS", "", VAR_GLOBAL);
   1428 	Var_Set(".ALLTARGETS", "", VAR_GLOBAL);
   1429 	/* some makefiles need to know this */
   1430 	Var_Set(MAKE_LEVEL ".ENV", MAKE_LEVEL_ENV, VAR_CMDLINE);
   1431 
   1432 	/*
   1433 	 * Set some other useful macros
   1434 	 */
   1435 	{
   1436 	    char tmp[64], *ep;
   1437 
   1438 	    makelevel = ((ep = getenv(MAKE_LEVEL_ENV)) && *ep) ? atoi(ep) : 0;
   1439 	    if (makelevel < 0)
   1440 		makelevel = 0;
   1441 	    snprintf(tmp, sizeof(tmp), "%d", makelevel);
   1442 	    Var_Set(MAKE_LEVEL, tmp, VAR_GLOBAL);
   1443 	    snprintf(tmp, sizeof(tmp), "%u", myPid);
   1444 	    Var_Set(".MAKE.PID", tmp, VAR_GLOBAL);
   1445 	    snprintf(tmp, sizeof(tmp), "%u", getppid());
   1446 	    Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL);
   1447 	}
   1448 	if (makelevel > 0) {
   1449 		char pn[1024];
   1450 		snprintf(pn, sizeof(pn), "%s[%d]", progname, makelevel);
   1451 		progname = bmake_strdup(pn);
   1452 	}
   1453 
   1454 #ifdef USE_META
   1455 	meta_init();
   1456 #endif
   1457 	Dir_Init();
   1458 
   1459 	/*
   1460 	 * First snag any flags out of the MAKE environment variable.
   1461 	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
   1462 	 * in a different format).
   1463 	 */
   1464 #ifdef POSIX
   1465 	{
   1466 	    char *p1 = explode(getenv("MAKEFLAGS"));
   1467 	    Main_ParseArgLine(p1);
   1468 	    free(p1);
   1469 	}
   1470 #else
   1471 	Main_ParseArgLine(getenv("MAKE"));
   1472 #endif
   1473 
   1474 	/*
   1475 	 * Find where we are (now).
   1476 	 * We take care of PWD for the automounter below...
   1477 	 */
   1478 	if (getcwd(curdir, MAXPATHLEN) == NULL) {
   1479 		(void)fprintf(stderr, "%s: getcwd: %s.\n",
   1480 		    progname, strerror(errno));
   1481 		exit(2);
   1482 	}
   1483 
   1484 	MainParseArgs(argc, argv);
   1485 
   1486 	if (opts.enterFlag)
   1487 		printf("%s: Entering directory `%s'\n", progname, curdir);
   1488 
   1489 	/*
   1490 	 * Verify that cwd is sane.
   1491 	 */
   1492 	if (stat(curdir, &sa) == -1) {
   1493 	    (void)fprintf(stderr, "%s: %s: %s.\n",
   1494 		 progname, curdir, strerror(errno));
   1495 	    exit(2);
   1496 	}
   1497 
   1498 #ifndef NO_PWD_OVERRIDE
   1499 	HandlePWD(&sa);
   1500 #endif
   1501 	Var_Set(".CURDIR", curdir, VAR_GLOBAL);
   1502 
   1503 	InitObjdir(machine, machine_arch);
   1504 
   1505 	/*
   1506 	 * Initialize archive, target and suffix modules in preparation for
   1507 	 * parsing the makefile(s)
   1508 	 */
   1509 	Arch_Init();
   1510 	Targ_Init();
   1511 	Suff_Init();
   1512 	Trace_Init(tracefile);
   1513 
   1514 	DEFAULT = NULL;
   1515 	(void)time(&now);
   1516 
   1517 	Trace_Log(MAKESTART, NULL);
   1518 
   1519 	InitVarTargets();
   1520 
   1521 	InitDefSysIncPath(syspath);
   1522 
   1523 	/*
   1524 	 * Read in the built-in rules first, followed by the specified
   1525 	 * makefiles, or the default makefile and Makefile, in that order,
   1526 	 * if no makefiles were given on the command line.
   1527 	 */
   1528 	if (!opts.noBuiltins)
   1529 		ReadBuiltinRules();
   1530 	ReadMakefiles();
   1531 
   1532 	/* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
   1533 	if (!opts.noBuiltins || !opts.printVars) {
   1534 	    /* ignore /dev/null and anything starting with "no" */
   1535 	    (void)Var_Subst("${.MAKE.DEPENDFILE:N/dev/null:Nno*:T}",
   1536 			    VAR_CMDLINE, VARE_WANTRES, &makeDependfile);
   1537 	    if (makeDependfile[0] != '\0') {
   1538 		/* TODO: handle errors */
   1539 		doing_depend = TRUE;
   1540 		(void)ReadMakefile(makeDependfile);
   1541 		doing_depend = FALSE;
   1542 	    }
   1543 	}
   1544 
   1545 	if (enterFlagObj)
   1546 		printf("%s: Entering directory `%s'\n", progname, objdir);
   1547 
   1548 	MakeMode(NULL);
   1549 
   1550 	{
   1551 	    void *freeIt;
   1552 	    Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &freeIt),
   1553 		       VAR_GLOBAL);
   1554 	    bmake_free(freeIt);
   1555 
   1556 	}
   1557 
   1558 	InitMaxJobs();
   1559 
   1560 	/*
   1561 	 * Be compatible if user did not specify -j and did not explicitly
   1562 	 * turned compatibility on
   1563 	 */
   1564 	if (!opts.compatMake && !forceJobs) {
   1565 	    opts.compatMake = TRUE;
   1566 	}
   1567 
   1568 	if (!opts.compatMake)
   1569 	    Job_ServerStart(maxJobTokens, jp_0, jp_1);
   1570 	DEBUG5(JOB, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
   1571 	       jp_0, jp_1, opts.maxJobs, maxJobTokens, opts.compatMake ? 1 : 0);
   1572 
   1573 	if (!opts.printVars)
   1574 	    Main_ExportMAKEFLAGS(TRUE);	/* initial export */
   1575 
   1576 	InitVpath();
   1577 
   1578 	/*
   1579 	 * Now that all search paths have been read for suffixes et al, it's
   1580 	 * time to add the default search path to their lists...
   1581 	 */
   1582 	Suff_DoPaths();
   1583 
   1584 	/*
   1585 	 * Propagate attributes through :: dependency lists.
   1586 	 */
   1587 	Targ_Propagate();
   1588 
   1589 	/* print the initial graph, if the user requested it */
   1590 	if (DEBUG(GRAPH1))
   1591 		Targ_PrintGraph(1);
   1592 
   1593 	/* print the values of any variables requested by the user */
   1594 	if (opts.printVars) {
   1595 		doPrintVars();
   1596 		outOfDate = FALSE;
   1597 	} else {
   1598 		outOfDate = runTargets();
   1599 	}
   1600 
   1601 	CleanUp();
   1602 
   1603 	return outOfDate ? 1 : 0;
   1604 }
   1605 
   1606 /* Open and parse the given makefile, with all its side effects.
   1607  *
   1608  * Results:
   1609  *	0 if ok. -1 if couldn't open file.
   1610  */
   1611 static int
   1612 ReadMakefile(const char *fname)
   1613 {
   1614 	int fd;
   1615 	char *name, *path = NULL;
   1616 
   1617 	if (!strcmp(fname, "-")) {
   1618 		Parse_File(NULL /*stdin*/, -1);
   1619 		Var_Set("MAKEFILE", "", VAR_INTERNAL);
   1620 	} else {
   1621 		/* if we've chdir'd, rebuild the path name */
   1622 		if (strcmp(curdir, objdir) && *fname != '/') {
   1623 			path = str_concat3(curdir, "/", fname);
   1624 			fd = open(path, O_RDONLY);
   1625 			if (fd != -1) {
   1626 				fname = path;
   1627 				goto found;
   1628 			}
   1629 			free(path);
   1630 
   1631 			/* If curdir failed, try objdir (ala .depend) */
   1632 			path = str_concat3(objdir, "/", fname);
   1633 			fd = open(path, O_RDONLY);
   1634 			if (fd != -1) {
   1635 				fname = path;
   1636 				goto found;
   1637 			}
   1638 		} else {
   1639 			fd = open(fname, O_RDONLY);
   1640 			if (fd != -1)
   1641 				goto found;
   1642 		}
   1643 		/* look in -I and system include directories. */
   1644 		name = Dir_FindFile(fname, parseIncPath);
   1645 		if (!name) {
   1646 			SearchPath *sysInc = Lst_IsEmpty(sysIncPath)
   1647 					     ? defSysIncPath : sysIncPath;
   1648 			name = Dir_FindFile(fname, sysInc);
   1649 		}
   1650 		if (!name || (fd = open(name, O_RDONLY)) == -1) {
   1651 			free(name);
   1652 			free(path);
   1653 			return -1;
   1654 		}
   1655 		fname = name;
   1656 		/*
   1657 		 * set the MAKEFILE variable desired by System V fans -- the
   1658 		 * placement of the setting here means it gets set to the last
   1659 		 * makefile specified, as it is set by SysV make.
   1660 		 */
   1661 found:
   1662 		if (!doing_depend)
   1663 			Var_Set("MAKEFILE", fname, VAR_INTERNAL);
   1664 		Parse_File(fname, fd);
   1665 	}
   1666 	free(path);
   1667 	return 0;
   1668 }
   1669 
   1670 
   1671 
   1672 /*-
   1673  * Cmd_Exec --
   1674  *	Execute the command in cmd, and return the output of that command
   1675  *	in a string.  In the output, newlines are replaced with spaces.
   1676  *
   1677  * Results:
   1678  *	A string containing the output of the command, or the empty string.
   1679  *	*errfmt returns a format string describing the command failure,
   1680  *	if any, using a single %s conversion specification.
   1681  *
   1682  * Side Effects:
   1683  *	The string must be freed by the caller.
   1684  */
   1685 char *
   1686 Cmd_Exec(const char *cmd, const char **errfmt)
   1687 {
   1688     const char	*args[4];	/* Args for invoking the shell */
   1689     int		fds[2];		/* Pipe streams */
   1690     int		cpid;		/* Child PID */
   1691     int		pid;		/* PID from wait() */
   1692     int		status;		/* command exit status */
   1693     Buffer	buf;		/* buffer to store the result */
   1694     ssize_t	bytes_read;
   1695     char	*res;		/* result */
   1696     size_t	res_len;
   1697     char	*cp;
   1698     int		savederr;	/* saved errno */
   1699 
   1700     *errfmt = NULL;
   1701 
   1702     if (!shellName)
   1703 	Shell_Init();
   1704     /*
   1705      * Set up arguments for shell
   1706      */
   1707     args[0] = shellName;
   1708     args[1] = "-c";
   1709     args[2] = cmd;
   1710     args[3] = NULL;
   1711 
   1712     /*
   1713      * Open a pipe for fetching its output
   1714      */
   1715     if (pipe(fds) == -1) {
   1716 	*errfmt = "Couldn't create pipe for \"%s\"";
   1717 	goto bad;
   1718     }
   1719 
   1720     /*
   1721      * Fork
   1722      */
   1723     switch (cpid = vFork()) {
   1724     case 0:
   1725 	/*
   1726 	 * Close input side of pipe
   1727 	 */
   1728 	(void)close(fds[0]);
   1729 
   1730 	/*
   1731 	 * Duplicate the output stream to the shell's output, then
   1732 	 * shut the extra thing down. Note we don't fetch the error
   1733 	 * stream...why not? Why?
   1734 	 */
   1735 	(void)dup2(fds[1], 1);
   1736 	(void)close(fds[1]);
   1737 
   1738 	Var_ExportVars();
   1739 
   1740 	(void)execv(shellPath, UNCONST(args));
   1741 	_exit(1);
   1742 	/*NOTREACHED*/
   1743 
   1744     case -1:
   1745 	*errfmt = "Couldn't exec \"%s\"";
   1746 	goto bad;
   1747 
   1748     default:
   1749 	/*
   1750 	 * No need for the writing half
   1751 	 */
   1752 	(void)close(fds[1]);
   1753 
   1754 	savederr = 0;
   1755 	Buf_Init(&buf, 0);
   1756 
   1757 	do {
   1758 	    char   result[BUFSIZ];
   1759 	    bytes_read = read(fds[0], result, sizeof(result));
   1760 	    if (bytes_read > 0)
   1761 		Buf_AddBytes(&buf, result, (size_t)bytes_read);
   1762 	}
   1763 	while (bytes_read > 0 || (bytes_read == -1 && errno == EINTR));
   1764 	if (bytes_read == -1)
   1765 	    savederr = errno;
   1766 
   1767 	/*
   1768 	 * Close the input side of the pipe.
   1769 	 */
   1770 	(void)close(fds[0]);
   1771 
   1772 	/*
   1773 	 * Wait for the process to exit.
   1774 	 */
   1775 	while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) {
   1776 	    JobReapChild(pid, status, FALSE);
   1777 	    continue;
   1778 	}
   1779 	res_len = Buf_Len(&buf);
   1780 	res = Buf_Destroy(&buf, FALSE);
   1781 
   1782 	if (savederr != 0)
   1783 	    *errfmt = "Couldn't read shell's output for \"%s\"";
   1784 
   1785 	if (WIFSIGNALED(status))
   1786 	    *errfmt = "\"%s\" exited on a signal";
   1787 	else if (WEXITSTATUS(status) != 0)
   1788 	    *errfmt = "\"%s\" returned non-zero status";
   1789 
   1790 	/* Convert newlines to spaces.  A final newline is just stripped */
   1791 	if (res_len > 0 && res[res_len - 1] == '\n')
   1792 	    res[res_len - 1] = '\0';
   1793 	for (cp = res; *cp != '\0'; cp++)
   1794 	    if (*cp == '\n')
   1795 		*cp = ' ';
   1796 	break;
   1797     }
   1798     return res;
   1799 bad:
   1800     return bmake_strdup("");
   1801 }
   1802 
   1803 /* Print a printf-style error message.
   1804  *
   1805  * This error message has no consequences, in particular it does not affect
   1806  * the exit status. */
   1807 void
   1808 Error(const char *fmt, ...)
   1809 {
   1810 	va_list ap;
   1811 	FILE *err_file;
   1812 
   1813 	err_file = opts.debug_file;
   1814 	if (err_file == stdout)
   1815 		err_file = stderr;
   1816 	(void)fflush(stdout);
   1817 	for (;;) {
   1818 		va_start(ap, fmt);
   1819 		fprintf(err_file, "%s: ", progname);
   1820 		(void)vfprintf(err_file, fmt, ap);
   1821 		va_end(ap);
   1822 		(void)fprintf(err_file, "\n");
   1823 		(void)fflush(err_file);
   1824 		if (err_file == stderr)
   1825 			break;
   1826 		err_file = stderr;
   1827 	}
   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 errors)
   1893 {
   1894 	if (dieQuietly(NULL, -1))
   1895 		exit(2);
   1896 	Fatal("%d error%s", errors, errors == 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