Home | History | Annotate | Line # | Download | only in make
main.c revision 1.446
      1 /*	$NetBSD: main.c,v 1.446 2020/11/08 12:14:14 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.446 2020/11/08 12:14:14 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 static void
   1313 CleanUp(void)
   1314 {
   1315 #ifdef CLEANUP
   1316 	Lst_Destroy(opts.variables, free);
   1317 	Lst_Free(opts.makefiles);	/* don't free, may be used in GNodes */
   1318 	Lst_Destroy(opts.create, free);
   1319 #endif
   1320 
   1321 	/* print the graph now it's been processed if the user requested it */
   1322 	if (DEBUG(GRAPH2))
   1323 		Targ_PrintGraph(2);
   1324 
   1325 	Trace_Log(MAKEEND, NULL);
   1326 
   1327 	if (enterFlagObj)
   1328 		printf("%s: Leaving directory `%s'\n", progname, objdir);
   1329 	if (opts.enterFlag)
   1330 		printf("%s: Leaving directory `%s'\n", progname, curdir);
   1331 
   1332 #ifdef USE_META
   1333 	meta_finish();
   1334 #endif
   1335 	Suff_End();
   1336 	Targ_End();
   1337 	Arch_End();
   1338 	Var_End();
   1339 	Parse_End();
   1340 	Dir_End();
   1341 	Job_End();
   1342 	Trace_End();
   1343 }
   1344 
   1345 /*-
   1346  * main --
   1347  *	The main function, for obvious reasons. Initializes variables
   1348  *	and a few modules, then parses the arguments give it in the
   1349  *	environment and on the command line. Reads the system makefile
   1350  *	followed by either Makefile, makefile or the file given by the
   1351  *	-f argument. Sets the .MAKEFLAGS PMake variable based on all the
   1352  *	flags it has received by then uses either the Make or the Compat
   1353  *	module to create the initial list of targets.
   1354  *
   1355  * Results:
   1356  *	If -q was given, exits -1 if anything was out-of-date. Else it exits
   1357  *	0.
   1358  *
   1359  * Side Effects:
   1360  *	The program exits when done. Targets are created. etc. etc. etc.
   1361  */
   1362 int
   1363 main(int argc, char **argv)
   1364 {
   1365 	Boolean outOfDate;	/* FALSE if all targets up to date */
   1366 	struct stat sa;
   1367 	const char *machine;
   1368 	const char *machine_arch;
   1369 	char *syspath = getenv("MAKESYSPATH");
   1370 	struct utsname utsname;
   1371 
   1372 	/* default to writing debug to stderr */
   1373 	opts.debug_file = stderr;
   1374 
   1375 #ifdef SIGINFO
   1376 	(void)bmake_signal(SIGINFO, siginfo);
   1377 #endif
   1378 
   1379 	InitRandom();
   1380 
   1381 	if ((progname = strrchr(argv[0], '/')) != NULL)
   1382 		progname++;
   1383 	else
   1384 		progname = argv[0];
   1385 
   1386 	UnlimitFiles();
   1387 
   1388 	if (uname(&utsname) == -1) {
   1389 	    (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
   1390 		strerror(errno));
   1391 	    exit(2);
   1392 	}
   1393 
   1394 	/*
   1395 	 * Get the name of this type of MACHINE from utsname
   1396 	 * so we can share an executable for similar machines.
   1397 	 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
   1398 	 *
   1399 	 * Note that both MACHINE and MACHINE_ARCH are decided at
   1400 	 * run-time.
   1401 	 */
   1402 	machine = init_machine(&utsname);
   1403 	machine_arch = init_machine_arch();
   1404 
   1405 	myPid = getpid();		/* remember this for vFork() */
   1406 
   1407 	/*
   1408 	 * Just in case MAKEOBJDIR wants us to do something tricky.
   1409 	 */
   1410 	Var_Init();		/* Initialize the lists of variables for
   1411 				 * parsing arguments */
   1412 	Var_Set(".MAKE.OS", utsname.sysname, VAR_GLOBAL);
   1413 	Var_Set("MACHINE", machine, VAR_GLOBAL);
   1414 	Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
   1415 #ifdef MAKE_VERSION
   1416 	Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
   1417 #endif
   1418 	Var_Set(".newline", "\n", VAR_GLOBAL); /* handy for :@ loops */
   1419 	/*
   1420 	 * This is the traditional preference for makefiles.
   1421 	 */
   1422 #ifndef MAKEFILE_PREFERENCE_LIST
   1423 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
   1424 #endif
   1425 	Var_Set(MAKE_MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST,
   1426 		VAR_GLOBAL);
   1427 	Var_Set(MAKE_DEPENDFILE, ".depend", VAR_GLOBAL);
   1428 
   1429 	CmdOpts_Init();
   1430 	allPrecious = FALSE;		/* Remove targets when interrupted */
   1431 	deleteOnError = FALSE;		/* Historical default behavior */
   1432 	jobsRunning = FALSE;
   1433 
   1434 	maxJobTokens = opts.maxJobs;
   1435 	ignorePWD = FALSE;
   1436 
   1437 	/*
   1438 	 * Initialize the parsing, directory and variable modules to prepare
   1439 	 * for the reading of inclusion paths and variable settings on the
   1440 	 * command line
   1441 	 */
   1442 
   1443 	/*
   1444 	 * Initialize various variables.
   1445 	 *	MAKE also gets this name, for compatibility
   1446 	 *	.MAKEFLAGS gets set to the empty string just in case.
   1447 	 *	MFLAGS also gets initialized empty, for compatibility.
   1448 	 */
   1449 	Parse_Init();
   1450 	InitVarMake(argv[0]);
   1451 	Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
   1452 	Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL);
   1453 	Var_Set("MFLAGS", "", VAR_GLOBAL);
   1454 	Var_Set(".ALLTARGETS", "", VAR_GLOBAL);
   1455 	/* some makefiles need to know this */
   1456 	Var_Set(MAKE_LEVEL ".ENV", MAKE_LEVEL_ENV, VAR_CMDLINE);
   1457 
   1458 	/*
   1459 	 * Set some other useful macros
   1460 	 */
   1461 	{
   1462 	    char tmp[64], *ep = getenv(MAKE_LEVEL_ENV);
   1463 
   1464 	    makelevel = ep != NULL && ep[0] != '\0' ? atoi(ep) : 0;
   1465 	    if (makelevel < 0)
   1466 		makelevel = 0;
   1467 	    snprintf(tmp, sizeof tmp, "%d", makelevel);
   1468 	    Var_Set(MAKE_LEVEL, tmp, VAR_GLOBAL);
   1469 	    snprintf(tmp, sizeof tmp, "%u", myPid);
   1470 	    Var_Set(".MAKE.PID", tmp, VAR_GLOBAL);
   1471 	    snprintf(tmp, sizeof tmp, "%u", getppid());
   1472 	    Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL);
   1473 	}
   1474 	if (makelevel > 0) {
   1475 		char pn[1024];
   1476 		snprintf(pn, sizeof pn, "%s[%d]", progname, makelevel);
   1477 		progname = bmake_strdup(pn);
   1478 	}
   1479 
   1480 #ifdef USE_META
   1481 	meta_init();
   1482 #endif
   1483 	Dir_Init();
   1484 
   1485 	/*
   1486 	 * First snag any flags out of the MAKE environment variable.
   1487 	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
   1488 	 * in a different format).
   1489 	 */
   1490 #ifdef POSIX
   1491 	{
   1492 	    char *p1 = explode(getenv("MAKEFLAGS"));
   1493 	    Main_ParseArgLine(p1);
   1494 	    free(p1);
   1495 	}
   1496 #else
   1497 	Main_ParseArgLine(getenv("MAKE"));
   1498 #endif
   1499 
   1500 	/*
   1501 	 * Find where we are (now).
   1502 	 * We take care of PWD for the automounter below...
   1503 	 */
   1504 	if (getcwd(curdir, MAXPATHLEN) == NULL) {
   1505 		(void)fprintf(stderr, "%s: getcwd: %s.\n",
   1506 		    progname, strerror(errno));
   1507 		exit(2);
   1508 	}
   1509 
   1510 	MainParseArgs(argc, argv);
   1511 
   1512 	if (opts.enterFlag)
   1513 		printf("%s: Entering directory `%s'\n", progname, curdir);
   1514 
   1515 	/*
   1516 	 * Verify that cwd is sane.
   1517 	 */
   1518 	if (stat(curdir, &sa) == -1) {
   1519 	    (void)fprintf(stderr, "%s: %s: %s.\n",
   1520 		 progname, curdir, strerror(errno));
   1521 	    exit(2);
   1522 	}
   1523 
   1524 #ifndef NO_PWD_OVERRIDE
   1525 	HandlePWD(&sa);
   1526 #endif
   1527 	Var_Set(".CURDIR", curdir, VAR_GLOBAL);
   1528 
   1529 	InitObjdir(machine, machine_arch);
   1530 
   1531 	/*
   1532 	 * Initialize archive, target and suffix modules in preparation for
   1533 	 * parsing the makefile(s)
   1534 	 */
   1535 	Arch_Init();
   1536 	Targ_Init();
   1537 	Suff_Init();
   1538 	Trace_Init(tracefile);
   1539 
   1540 	DEFAULT = NULL;
   1541 	(void)time(&now);
   1542 
   1543 	Trace_Log(MAKESTART, NULL);
   1544 
   1545 	InitVarTargets();
   1546 
   1547 	InitDefSysIncPath(syspath);
   1548 
   1549 	/*
   1550 	 * Read in the built-in rules first, followed by the specified
   1551 	 * makefiles, or the default makefile and Makefile, in that order,
   1552 	 * if no makefiles were given on the command line.
   1553 	 */
   1554 	if (!opts.noBuiltins)
   1555 		ReadBuiltinRules();
   1556 	if (!Lst_IsEmpty(opts.makefiles))
   1557 		ReadAllMakefiles(opts.makefiles);
   1558 	else
   1559 		ReadFirstDefaultMakefile();
   1560 
   1561 	/* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
   1562 	if (!opts.noBuiltins || opts.printVars == PVM_NONE) {
   1563 	    /* ignore /dev/null and anything starting with "no" */
   1564 	    (void)Var_Subst("${.MAKE.DEPENDFILE:N/dev/null:Nno*:T}",
   1565 			    VAR_CMDLINE, VARE_WANTRES, &makeDependfile);
   1566 	    if (makeDependfile[0] != '\0') {
   1567 		/* TODO: handle errors */
   1568 		doing_depend = TRUE;
   1569 		(void)ReadMakefile(makeDependfile);
   1570 		doing_depend = FALSE;
   1571 	    }
   1572 	}
   1573 
   1574 	if (enterFlagObj)
   1575 		printf("%s: Entering directory `%s'\n", progname, objdir);
   1576 
   1577 	MakeMode(NULL);
   1578 
   1579 	{
   1580 	    void *freeIt;
   1581 	    Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &freeIt),
   1582 		       VAR_GLOBAL);
   1583 	    bmake_free(freeIt);
   1584 
   1585 	}
   1586 
   1587 	InitMaxJobs();
   1588 
   1589 	/*
   1590 	 * Be compatible if user did not specify -j and did not explicitly
   1591 	 * turned compatibility on
   1592 	 */
   1593 	if (!opts.compatMake && !forceJobs) {
   1594 	    opts.compatMake = TRUE;
   1595 	}
   1596 
   1597 	if (!opts.compatMake)
   1598 	    Job_ServerStart(maxJobTokens, jp_0, jp_1);
   1599 	DEBUG5(JOB, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
   1600 	       jp_0, jp_1, opts.maxJobs, maxJobTokens, opts.compatMake ? 1 : 0);
   1601 
   1602 	if (opts.printVars == PVM_NONE)
   1603 	    Main_ExportMAKEFLAGS(TRUE);	/* initial export */
   1604 
   1605 	InitVpath();
   1606 
   1607 	/*
   1608 	 * Now that all search paths have been read for suffixes et al, it's
   1609 	 * time to add the default search path to their lists...
   1610 	 */
   1611 	Suff_DoPaths();
   1612 
   1613 	/*
   1614 	 * Propagate attributes through :: dependency lists.
   1615 	 */
   1616 	Targ_Propagate();
   1617 
   1618 	/* print the initial graph, if the user requested it */
   1619 	if (DEBUG(GRAPH1))
   1620 		Targ_PrintGraph(1);
   1621 
   1622 	/* print the values of any variables requested by the user */
   1623 	if (opts.printVars != PVM_NONE) {
   1624 		doPrintVars();
   1625 		outOfDate = FALSE;
   1626 	} else {
   1627 		outOfDate = runTargets();
   1628 	}
   1629 
   1630 	CleanUp();
   1631 
   1632 	if (DEBUG(LINT) && (errors > 0 || Parse_GetFatals() > 0))
   1633 	    return 2;		/* Not 1 so -q can distinguish error */
   1634 	return outOfDate ? 1 : 0;
   1635 }
   1636 
   1637 /* Open and parse the given makefile, with all its side effects.
   1638  *
   1639  * Results:
   1640  *	0 if ok. -1 if couldn't open file.
   1641  */
   1642 static int
   1643 ReadMakefile(const char *fname)
   1644 {
   1645 	int fd;
   1646 	char *name, *path = NULL;
   1647 
   1648 	if (!strcmp(fname, "-")) {
   1649 		Parse_File(NULL /*stdin*/, -1);
   1650 		Var_Set("MAKEFILE", "", VAR_INTERNAL);
   1651 	} else {
   1652 		/* if we've chdir'd, rebuild the path name */
   1653 		if (strcmp(curdir, objdir) && *fname != '/') {
   1654 			path = str_concat3(curdir, "/", fname);
   1655 			fd = open(path, O_RDONLY);
   1656 			if (fd != -1) {
   1657 				fname = path;
   1658 				goto found;
   1659 			}
   1660 			free(path);
   1661 
   1662 			/* If curdir failed, try objdir (ala .depend) */
   1663 			path = str_concat3(objdir, "/", fname);
   1664 			fd = open(path, O_RDONLY);
   1665 			if (fd != -1) {
   1666 				fname = path;
   1667 				goto found;
   1668 			}
   1669 		} else {
   1670 			fd = open(fname, O_RDONLY);
   1671 			if (fd != -1)
   1672 				goto found;
   1673 		}
   1674 		/* look in -I and system include directories. */
   1675 		name = Dir_FindFile(fname, parseIncPath);
   1676 		if (!name) {
   1677 			SearchPath *sysInc = Lst_IsEmpty(sysIncPath)
   1678 					     ? defSysIncPath : sysIncPath;
   1679 			name = Dir_FindFile(fname, sysInc);
   1680 		}
   1681 		if (!name || (fd = open(name, O_RDONLY)) == -1) {
   1682 			free(name);
   1683 			free(path);
   1684 			return -1;
   1685 		}
   1686 		fname = name;
   1687 		/*
   1688 		 * set the MAKEFILE variable desired by System V fans -- the
   1689 		 * placement of the setting here means it gets set to the last
   1690 		 * makefile specified, as it is set by SysV make.
   1691 		 */
   1692 found:
   1693 		if (!doing_depend)
   1694 			Var_Set("MAKEFILE", fname, VAR_INTERNAL);
   1695 		Parse_File(fname, fd);
   1696 	}
   1697 	free(path);
   1698 	return 0;
   1699 }
   1700 
   1701 
   1702 
   1703 /*-
   1704  * Cmd_Exec --
   1705  *	Execute the command in cmd, and return the output of that command
   1706  *	in a string.  In the output, newlines are replaced with spaces.
   1707  *
   1708  * Results:
   1709  *	A string containing the output of the command, or the empty string.
   1710  *	*errfmt returns a format string describing the command failure,
   1711  *	if any, using a single %s conversion specification.
   1712  *
   1713  * Side Effects:
   1714  *	The string must be freed by the caller.
   1715  */
   1716 char *
   1717 Cmd_Exec(const char *cmd, const char **errfmt)
   1718 {
   1719     const char	*args[4];	/* Args for invoking the shell */
   1720     int		fds[2];		/* Pipe streams */
   1721     int		cpid;		/* Child PID */
   1722     int		pid;		/* PID from wait() */
   1723     int		status;		/* command exit status */
   1724     Buffer	buf;		/* buffer to store the result */
   1725     ssize_t	bytes_read;
   1726     char	*res;		/* result */
   1727     size_t	res_len;
   1728     char	*cp;
   1729     int		savederr;	/* saved errno */
   1730 
   1731     *errfmt = NULL;
   1732 
   1733     if (!shellName)
   1734 	Shell_Init();
   1735     /*
   1736      * Set up arguments for shell
   1737      */
   1738     args[0] = shellName;
   1739     args[1] = "-c";
   1740     args[2] = cmd;
   1741     args[3] = NULL;
   1742 
   1743     /*
   1744      * Open a pipe for fetching its output
   1745      */
   1746     if (pipe(fds) == -1) {
   1747 	*errfmt = "Couldn't create pipe for \"%s\"";
   1748 	goto bad;
   1749     }
   1750 
   1751     /*
   1752      * Fork
   1753      */
   1754     switch (cpid = vFork()) {
   1755     case 0:
   1756 	(void)close(fds[0]);	/* Close input side of pipe */
   1757 
   1758 	/*
   1759 	 * Duplicate the output stream to the shell's output, then
   1760 	 * shut the extra thing down. Note we don't fetch the error
   1761 	 * stream...why not? Why?
   1762 	 */
   1763 	(void)dup2(fds[1], 1);
   1764 	(void)close(fds[1]);
   1765 
   1766 	Var_ExportVars();
   1767 
   1768 	(void)execv(shellPath, UNCONST(args));
   1769 	_exit(1);
   1770 	/*NOTREACHED*/
   1771 
   1772     case -1:
   1773 	*errfmt = "Couldn't exec \"%s\"";
   1774 	goto bad;
   1775 
   1776     default:
   1777 	(void)close(fds[1]);	/* No need for the writing half */
   1778 
   1779 	savederr = 0;
   1780 	Buf_Init(&buf);
   1781 
   1782 	do {
   1783 	    char result[BUFSIZ];
   1784 	    bytes_read = read(fds[0], result, sizeof result);
   1785 	    if (bytes_read > 0)
   1786 		Buf_AddBytes(&buf, result, (size_t)bytes_read);
   1787 	} while (bytes_read > 0 || (bytes_read == -1 && errno == EINTR));
   1788 	if (bytes_read == -1)
   1789 	    savederr = errno;
   1790 
   1791 	(void)close(fds[0]);	/* Close the input side of the pipe. */
   1792 
   1793 	/* Wait for the process to exit. */
   1794 	while((pid = waitpid(cpid, &status, 0)) != cpid && pid >= 0)
   1795 	    JobReapChild(pid, status, FALSE);
   1796 
   1797 	res_len = Buf_Len(&buf);
   1798 	res = Buf_Destroy(&buf, FALSE);
   1799 
   1800 	if (savederr != 0)
   1801 	    *errfmt = "Couldn't read shell's output for \"%s\"";
   1802 
   1803 	if (WIFSIGNALED(status))
   1804 	    *errfmt = "\"%s\" exited on a signal";
   1805 	else if (WEXITSTATUS(status) != 0)
   1806 	    *errfmt = "\"%s\" returned non-zero status";
   1807 
   1808 	/* Convert newlines to spaces.  A final newline is just stripped */
   1809 	if (res_len > 0 && res[res_len - 1] == '\n')
   1810 	    res[res_len - 1] = '\0';
   1811 	for (cp = res; *cp != '\0'; cp++)
   1812 	    if (*cp == '\n')
   1813 		*cp = ' ';
   1814 	break;
   1815     }
   1816     return res;
   1817 bad:
   1818     return bmake_strdup("");
   1819 }
   1820 
   1821 /* Print a printf-style error message.
   1822  *
   1823  * In default mode, this error message has no consequences, in particular it
   1824  * does not affect the exit status.  Only in lint mode (-dL) it does. */
   1825 void
   1826 Error(const char *fmt, ...)
   1827 {
   1828 	va_list ap;
   1829 	FILE *err_file;
   1830 
   1831 	err_file = opts.debug_file;
   1832 	if (err_file == stdout)
   1833 		err_file = stderr;
   1834 	(void)fflush(stdout);
   1835 	for (;;) {
   1836 		va_start(ap, fmt);
   1837 		fprintf(err_file, "%s: ", progname);
   1838 		(void)vfprintf(err_file, fmt, ap);
   1839 		va_end(ap);
   1840 		(void)fprintf(err_file, "\n");
   1841 		(void)fflush(err_file);
   1842 		if (err_file == stderr)
   1843 			break;
   1844 		err_file = stderr;
   1845 	}
   1846 	errors++;
   1847 }
   1848 
   1849 /* Produce a Fatal error message, then exit immediately.
   1850  *
   1851  * If jobs are running, wait for them to finish. */
   1852 void
   1853 Fatal(const char *fmt, ...)
   1854 {
   1855 	va_list ap;
   1856 
   1857 	va_start(ap, fmt);
   1858 	if (jobsRunning)
   1859 		Job_Wait();
   1860 
   1861 	(void)fflush(stdout);
   1862 	(void)vfprintf(stderr, fmt, ap);
   1863 	va_end(ap);
   1864 	(void)fprintf(stderr, "\n");
   1865 	(void)fflush(stderr);
   1866 
   1867 	PrintOnError(NULL, NULL);
   1868 
   1869 	if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
   1870 		Targ_PrintGraph(2);
   1871 	Trace_Log(MAKEERROR, NULL);
   1872 	exit(2);		/* Not 1 so -q can distinguish error */
   1873 }
   1874 
   1875 /* Major exception once jobs are being created.
   1876  * Kills all jobs, prints a message and exits. */
   1877 void
   1878 Punt(const char *fmt, ...)
   1879 {
   1880 	va_list ap;
   1881 
   1882 	va_start(ap, fmt);
   1883 	(void)fflush(stdout);
   1884 	(void)fprintf(stderr, "%s: ", progname);
   1885 	(void)vfprintf(stderr, fmt, ap);
   1886 	va_end(ap);
   1887 	(void)fprintf(stderr, "\n");
   1888 	(void)fflush(stderr);
   1889 
   1890 	PrintOnError(NULL, NULL);
   1891 
   1892 	DieHorribly();
   1893 }
   1894 
   1895 /* Exit without giving a message. */
   1896 void
   1897 DieHorribly(void)
   1898 {
   1899 	if (jobsRunning)
   1900 		Job_AbortAll();
   1901 	if (DEBUG(GRAPH2))
   1902 		Targ_PrintGraph(2);
   1903 	Trace_Log(MAKEERROR, NULL);
   1904 	exit(2);		/* Not 1, so -q can distinguish error */
   1905 }
   1906 
   1907 /* Called when aborting due to errors in child shell to signal abnormal exit.
   1908  * The program exits.
   1909  * Errors is the number of errors encountered in Make_Make. */
   1910 void
   1911 Finish(int errs)
   1912 {
   1913 	if (shouldDieQuietly(NULL, -1))
   1914 		exit(2);
   1915 	Fatal("%d error%s", errs, errs == 1 ? "" : "s");
   1916 }
   1917 
   1918 /*
   1919  * eunlink --
   1920  *	Remove a file carefully, avoiding directories.
   1921  */
   1922 int
   1923 eunlink(const char *file)
   1924 {
   1925 	struct stat st;
   1926 
   1927 	if (lstat(file, &st) == -1)
   1928 		return -1;
   1929 
   1930 	if (S_ISDIR(st.st_mode)) {
   1931 		errno = EISDIR;
   1932 		return -1;
   1933 	}
   1934 	return unlink(file);
   1935 }
   1936 
   1937 static void
   1938 write_all(int fd, const void *data, size_t n)
   1939 {
   1940 	const char *mem = data;
   1941 
   1942 	while (n > 0) {
   1943 		ssize_t written = write(fd, mem, n);
   1944 		if (written == -1 && errno == EAGAIN)
   1945 			continue;
   1946 		if (written == -1)
   1947 			break;
   1948 		mem += written;
   1949 		n -= (size_t)written;
   1950 	}
   1951 }
   1952 
   1953 /*
   1954  * execDie --
   1955  *	Print why exec failed, avoiding stdio.
   1956  */
   1957 void MAKE_ATTR_DEAD
   1958 execDie(const char *af, const char *av)
   1959 {
   1960 	Buffer buf;
   1961 
   1962 	Buf_Init(&buf);
   1963 	Buf_AddStr(&buf, progname);
   1964 	Buf_AddStr(&buf, ": ");
   1965 	Buf_AddStr(&buf, af);
   1966 	Buf_AddStr(&buf, "(");
   1967 	Buf_AddStr(&buf, av);
   1968 	Buf_AddStr(&buf, ") failed (");
   1969 	Buf_AddStr(&buf, strerror(errno));
   1970 	Buf_AddStr(&buf, ")\n");
   1971 
   1972 	write_all(STDERR_FILENO, Buf_GetAll(&buf, NULL), Buf_Len(&buf));
   1973 
   1974 	Buf_Destroy(&buf, TRUE);
   1975 	_exit(1);
   1976 }
   1977 
   1978 /*
   1979  * usage --
   1980  *	exit with usage message
   1981  */
   1982 static void
   1983 usage(void)
   1984 {
   1985 	char *p;
   1986 	if ((p = strchr(progname, '[')) != NULL)
   1987 		*p = '\0';
   1988 
   1989 	(void)fprintf(stderr,
   1990 "usage: %s [-BeikNnqrstWwX] \n"
   1991 "            [-C directory] [-D variable] [-d flags] [-f makefile]\n"
   1992 "            [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n"
   1993 "            [-V variable] [-v variable] [variable=value] [target ...]\n",
   1994 	    progname);
   1995 	exit(2);
   1996 }
   1997 
   1998 /*
   1999  * realpath(3) can get expensive, cache results...
   2000  */
   2001 static GNode *cached_realpaths = NULL;
   2002 
   2003 static GNode *
   2004 get_cached_realpaths(void)
   2005 {
   2006 
   2007     if (!cached_realpaths) {
   2008 	cached_realpaths = Targ_NewGN("Realpath");
   2009 #ifndef DEBUG_REALPATH_CACHE
   2010 	cached_realpaths->flags = INTERNAL;
   2011 #endif
   2012     }
   2013 
   2014     return cached_realpaths;
   2015 }
   2016 
   2017 /* purge any relative paths */
   2018 static void
   2019 purge_cached_realpaths(void)
   2020 {
   2021     GNode *cache = get_cached_realpaths();
   2022     HashEntry *he, *nhe;
   2023     HashIter hi;
   2024 
   2025     HashIter_Init(&hi, &cache->context);
   2026     he = HashIter_Next(&hi);
   2027     while (he != NULL) {
   2028 	nhe = HashIter_Next(&hi);
   2029 	if (he->key[0] != '/') {
   2030 	    if (DEBUG(DIR))
   2031 		fprintf(stderr, "cached_realpath: purging %s\n", he->key);
   2032 	    HashTable_DeleteEntry(&cache->context, he);
   2033 	}
   2034 	he = nhe;
   2035     }
   2036 }
   2037 
   2038 char *
   2039 cached_realpath(const char *pathname, char *resolved)
   2040 {
   2041     GNode *cache;
   2042     const char *rp;
   2043     void *freeIt;
   2044 
   2045     if (pathname == NULL || pathname[0] == '\0')
   2046 	return NULL;
   2047 
   2048     cache = get_cached_realpaths();
   2049 
   2050     if ((rp = Var_Value(pathname, cache, &freeIt)) != NULL) {
   2051 	/* a hit */
   2052 	strncpy(resolved, rp, MAXPATHLEN);
   2053 	resolved[MAXPATHLEN - 1] = '\0';
   2054     } else if ((rp = realpath(pathname, resolved)) != NULL) {
   2055 	Var_Set(pathname, rp, cache);
   2056     } /* else should we negative-cache? */
   2057 
   2058     bmake_free(freeIt);
   2059     return rp ? resolved : NULL;
   2060 }
   2061 
   2062 /*
   2063  * Return true if we should die without noise.
   2064  * For example our failing child was a sub-make or failure happened elsewhere.
   2065  */
   2066 Boolean
   2067 shouldDieQuietly(GNode *gn, int bf)
   2068 {
   2069     static int quietly = -1;
   2070 
   2071     if (quietly < 0) {
   2072 	if (DEBUG(JOB) || !GetBooleanVar(".MAKE.DIE_QUIETLY", TRUE))
   2073 	    quietly = 0;
   2074 	else if (bf >= 0)
   2075 	    quietly = bf;
   2076 	else
   2077 	    quietly = gn != NULL && (gn->type & OP_MAKE);
   2078     }
   2079     return quietly;
   2080 }
   2081 
   2082 static void
   2083 SetErrorVars(GNode *gn)
   2084 {
   2085     StringListNode *ln;
   2086 
   2087     /*
   2088      * We can print this even if there is no .ERROR target.
   2089      */
   2090     Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL);
   2091     Var_Delete(".ERROR_CMD", VAR_GLOBAL);
   2092 
   2093     for (ln = gn->commands->first; ln != NULL; ln = ln->next) {
   2094 	const char *cmd = ln->datum;
   2095 
   2096 	if (cmd == NULL)
   2097 	    break;
   2098 	Var_Append(".ERROR_CMD", cmd, VAR_GLOBAL);
   2099     }
   2100 }
   2101 
   2102 void
   2103 PrintOnError(GNode *gn, const char *s)
   2104 {
   2105     static GNode *en = NULL;
   2106     const char *expr;
   2107     char *cp;
   2108 
   2109     if (DEBUG(HASH)) {
   2110 	Targ_Stats();
   2111 	Var_Stats();
   2112     }
   2113 
   2114     /* we generally want to keep quiet if a sub-make died */
   2115     if (shouldDieQuietly(gn, -1))
   2116 	return;
   2117 
   2118     if (s)
   2119 	printf("%s", s);
   2120 
   2121     printf("\n%s: stopped in %s\n", progname, curdir);
   2122 
   2123     if (en)
   2124 	return;				/* we've been here! */
   2125     if (gn)
   2126 	SetErrorVars(gn);
   2127     expr = "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}";
   2128     (void)Var_Subst(expr, VAR_GLOBAL, VARE_WANTRES, &cp);
   2129     /* TODO: handle errors */
   2130     printf("%s", cp);
   2131     free(cp);
   2132     fflush(stdout);
   2133 
   2134     /*
   2135      * Finally, see if there is a .ERROR target, and run it if so.
   2136      */
   2137     en = Targ_FindNode(".ERROR");
   2138     if (en) {
   2139 	en->type |= OP_SPECIAL;
   2140 	Compat_Make(en, en);
   2141     }
   2142 }
   2143 
   2144 void
   2145 Main_ExportMAKEFLAGS(Boolean first)
   2146 {
   2147     static Boolean once = TRUE;
   2148     const char *expr;
   2149     char *s;
   2150 
   2151     if (once != first)
   2152 	return;
   2153     once = FALSE;
   2154 
   2155     expr = "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}";
   2156     (void)Var_Subst(expr, VAR_CMDLINE, VARE_WANTRES, &s);
   2157     /* TODO: handle errors */
   2158     if (s[0] != '\0') {
   2159 #ifdef POSIX
   2160 	setenv("MAKEFLAGS", s, 1);
   2161 #else
   2162 	setenv("MAKE", s, 1);
   2163 #endif
   2164     }
   2165 }
   2166 
   2167 char *
   2168 getTmpdir(void)
   2169 {
   2170     static char *tmpdir = NULL;
   2171 
   2172     if (!tmpdir) {
   2173 	struct stat st;
   2174 
   2175 	/*
   2176 	 * Honor $TMPDIR but only if it is valid.
   2177 	 * Ensure it ends with /.
   2178 	 */
   2179 	(void)Var_Subst("${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL,
   2180 			VARE_WANTRES, &tmpdir);
   2181 	/* TODO: handle errors */
   2182 	if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
   2183 	    free(tmpdir);
   2184 	    tmpdir = bmake_strdup(_PATH_TMP);
   2185 	}
   2186     }
   2187     return tmpdir;
   2188 }
   2189 
   2190 /*
   2191  * Create and open a temp file using "pattern".
   2192  * If out_fname is provided, set it to a copy of the filename created.
   2193  * Otherwise unlink the file once open.
   2194  */
   2195 int
   2196 mkTempFile(const char *pattern, char **out_fname)
   2197 {
   2198     static char *tmpdir = NULL;
   2199     char tfile[MAXPATHLEN];
   2200     int fd;
   2201 
   2202     if (pattern == NULL)
   2203 	pattern = TMPPAT;
   2204     if (tmpdir == NULL)
   2205 	tmpdir = getTmpdir();
   2206     if (pattern[0] == '/') {
   2207 	snprintf(tfile, sizeof tfile, "%s", pattern);
   2208     } else {
   2209 	snprintf(tfile, sizeof tfile, "%s%s", tmpdir, pattern);
   2210     }
   2211     if ((fd = mkstemp(tfile)) < 0)
   2212 	Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
   2213     if (out_fname) {
   2214 	*out_fname = bmake_strdup(tfile);
   2215     } else {
   2216 	unlink(tfile);			/* we just want the descriptor */
   2217     }
   2218     return fd;
   2219 }
   2220 
   2221 /*
   2222  * Convert a string representation of a boolean.
   2223  * Anything that looks like "No", "False", "Off", "0" etc,
   2224  * is FALSE, otherwise TRUE.
   2225  */
   2226 Boolean
   2227 ParseBoolean(const char *s, Boolean bf)
   2228 {
   2229     switch(s[0]) {
   2230     case '\0':			/* not set - the default wins */
   2231 	break;
   2232     case '0':
   2233     case 'F':
   2234     case 'f':
   2235     case 'N':
   2236     case 'n':
   2237 	return FALSE;
   2238     case 'O':
   2239     case 'o':
   2240 	return s[1] != 'F' && s[1] != 'f';
   2241     default:
   2242 	return TRUE;
   2243     }
   2244     return bf;
   2245 }
   2246