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