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