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