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