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