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