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