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