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