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