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