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