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