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