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