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