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