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