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