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