xref: /netbsd-src/usr.bin/make/main.c (revision ba65fde2d7fefa7d39838fa5fa855e62bd606b5e)
1 /*	$NetBSD: main.c,v 1.207 2013/02/16 02:39:27 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.207 2013/02/16 02:39:27 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.207 2013/02/16 02:39:27 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 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_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 #ifdef 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 	/*
955 	 * First snag any flags out of the MAKE environment variable.
956 	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
957 	 * in a different format).
958 	 */
959 #ifdef POSIX
960 	Main_ParseArgLine(getenv("MAKEFLAGS"));
961 #else
962 	Main_ParseArgLine(getenv("MAKE"));
963 #endif
964 
965 	/*
966 	 * Find where we are (now).
967 	 * We take care of PWD for the automounter below...
968 	 */
969 	if (getcwd(curdir, MAXPATHLEN) == NULL) {
970 		(void)fprintf(stderr, "%s: getcwd: %s.\n",
971 		    progname, strerror(errno));
972 		exit(2);
973 	}
974 
975 	MainParseArgs(argc, argv);
976 
977 	/*
978 	 * Verify that cwd is sane.
979 	 */
980 	if (stat(curdir, &sa) == -1) {
981 	    (void)fprintf(stderr, "%s: %s: %s.\n",
982 		 progname, curdir, strerror(errno));
983 	    exit(2);
984 	}
985 
986 	/*
987 	 * All this code is so that we know where we are when we start up
988 	 * on a different machine with pmake.
989 	 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
990 	 * since the value of curdir can vary depending on how we got
991 	 * here.  Ie sitting at a shell prompt (shell that provides $PWD)
992 	 * or via subdir.mk in which case its likely a shell which does
993 	 * not provide it.
994 	 * So, to stop it breaking this case only, we ignore PWD if
995 	 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
996 	 */
997 	if (!ignorePWD &&
998 	    (pwd = getenv("PWD")) != NULL &&
999 	    getenv("MAKEOBJDIRPREFIX") == NULL) {
1000 		const char *makeobjdir = getenv("MAKEOBJDIR");
1001 
1002 		if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
1003 			if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
1004 			    sa.st_dev == sb.st_dev)
1005 				(void)strncpy(curdir, pwd, MAXPATHLEN);
1006 		}
1007 	}
1008 	Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0);
1009 
1010 	/*
1011 	 * Find the .OBJDIR.  If MAKEOBJDIRPREFIX, or failing that,
1012 	 * MAKEOBJDIR is set in the environment, try only that value
1013 	 * and fall back to .CURDIR if it does not exist.
1014 	 *
1015 	 * Otherwise, try _PATH_OBJDIR.MACHINE, _PATH_OBJDIR, and
1016 	 * finally _PATH_OBJDIRPREFIX`pwd`, in that order.  If none
1017 	 * of these paths exist, just use .CURDIR.
1018 	 */
1019 	Dir_Init(curdir);
1020 	(void)Main_SetObjdir(curdir);
1021 
1022 	if ((path = getenv("MAKEOBJDIRPREFIX")) != NULL) {
1023 		(void)snprintf(mdpath, MAXPATHLEN, "%s%s", path, curdir);
1024 		(void)Main_SetObjdir(mdpath);
1025 	} else if ((path = getenv("MAKEOBJDIR")) != NULL) {
1026 		(void)Main_SetObjdir(path);
1027 	} else {
1028 		(void)snprintf(mdpath, MAXPATHLEN, "%s.%s", _PATH_OBJDIR, machine);
1029 		if (!Main_SetObjdir(mdpath) && !Main_SetObjdir(_PATH_OBJDIR)) {
1030 			(void)snprintf(mdpath, MAXPATHLEN, "%s%s",
1031 					_PATH_OBJDIRPREFIX, curdir);
1032 			(void)Main_SetObjdir(mdpath);
1033 		}
1034 	}
1035 
1036 	/*
1037 	 * Be compatible if user did not specify -j and did not explicitly
1038 	 * turned compatibility on
1039 	 */
1040 	if (!compatMake && !forceJobs) {
1041 		compatMake = TRUE;
1042 	}
1043 
1044 	/*
1045 	 * Initialize archive, target and suffix modules in preparation for
1046 	 * parsing the makefile(s)
1047 	 */
1048 	Arch_Init();
1049 	Targ_Init();
1050 	Suff_Init();
1051 	Trace_Init(tracefile);
1052 
1053 	DEFAULT = NULL;
1054 	(void)time(&now);
1055 
1056 	Trace_Log(MAKESTART, NULL);
1057 
1058 	/*
1059 	 * Set up the .TARGETS variable to contain the list of targets to be
1060 	 * created. If none specified, make the variable empty -- the parser
1061 	 * will fill the thing in with the default or .MAIN target.
1062 	 */
1063 	if (!Lst_IsEmpty(create)) {
1064 		LstNode ln;
1065 
1066 		for (ln = Lst_First(create); ln != NULL;
1067 		    ln = Lst_Succ(ln)) {
1068 			char *name = (char *)Lst_Datum(ln);
1069 
1070 			Var_Append(".TARGETS", name, VAR_GLOBAL);
1071 		}
1072 	} else
1073 		Var_Set(".TARGETS", "", VAR_GLOBAL, 0);
1074 
1075 
1076 	/*
1077 	 * If no user-supplied system path was given (through the -m option)
1078 	 * add the directories from the DEFSYSPATH (more than one may be given
1079 	 * as dir1:...:dirn) to the system include path.
1080 	 */
1081 	if (syspath == NULL || *syspath == '\0')
1082 		syspath = defsyspath;
1083 	else
1084 		syspath = bmake_strdup(syspath);
1085 
1086 	for (start = syspath; *start != '\0'; start = cp) {
1087 		for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1088 			continue;
1089 		if (*cp == ':') {
1090 			*cp++ = '\0';
1091 		}
1092 		/* look for magic parent directory search string */
1093 		if (strncmp(".../", start, 4) != 0) {
1094 			(void)Dir_AddDir(defIncPath, start);
1095 		} else {
1096 			if (Dir_FindHereOrAbove(curdir, start+4,
1097 			    found_path, sizeof(found_path))) {
1098 				(void)Dir_AddDir(defIncPath, found_path);
1099 			}
1100 		}
1101 	}
1102 	if (syspath != defsyspath)
1103 		free(syspath);
1104 
1105 	/*
1106 	 * Read in the built-in rules first, followed by the specified
1107 	 * makefile, if it was (makefile != NULL), or the default
1108 	 * makefile and Makefile, in that order, if it wasn't.
1109 	 */
1110 	if (!noBuiltins) {
1111 		LstNode ln;
1112 
1113 		sysMkPath = Lst_Init(FALSE);
1114 		Dir_Expand(_PATH_DEFSYSMK,
1115 			   Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
1116 			   sysMkPath);
1117 		if (Lst_IsEmpty(sysMkPath))
1118 			Fatal("%s: no system rules (%s).", progname,
1119 			    _PATH_DEFSYSMK);
1120 		ln = Lst_Find(sysMkPath, NULL, ReadMakefile);
1121 		if (ln == NULL)
1122 			Fatal("%s: cannot open %s.", progname,
1123 			    (char *)Lst_Datum(ln));
1124 	}
1125 
1126 	if (!Lst_IsEmpty(makefiles)) {
1127 		LstNode ln;
1128 
1129 		ln = Lst_Find(makefiles, NULL, ReadAllMakefiles);
1130 		if (ln != NULL)
1131 			Fatal("%s: cannot open %s.", progname,
1132 			    (char *)Lst_Datum(ln));
1133 	} else {
1134 	    p1 = Var_Subst(NULL, "${" MAKEFILE_PREFERENCE "}",
1135 		VAR_CMD, 0);
1136 	    if (p1) {
1137 		(void)str2Lst_Append(makefiles, p1, NULL);
1138 		(void)Lst_Find(makefiles, NULL, ReadMakefile);
1139 		free(p1);
1140 	    }
1141 	}
1142 
1143 	/* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1144 	if (!noBuiltins || !printVars) {
1145 	    makeDependfile = Var_Subst(NULL, "${.MAKE.DEPENDFILE:T}",
1146 		VAR_CMD, 0);
1147 	    doing_depend = TRUE;
1148 	    (void)ReadMakefile(makeDependfile, NULL);
1149 	    doing_depend = FALSE;
1150 	}
1151 
1152 	MakeMode(NULL);
1153 
1154 	Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
1155 	if (p1)
1156 	    free(p1);
1157 
1158 	if (!compatMake)
1159 	    Job_ServerStart(maxJobTokens, jp_0, jp_1);
1160 	if (DEBUG(JOB))
1161 	    fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1162 		jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
1163 
1164 	Main_ExportMAKEFLAGS(TRUE);	/* initial export */
1165 
1166 
1167 	/*
1168 	 * For compatibility, look at the directories in the VPATH variable
1169 	 * and add them to the search path, if the variable is defined. The
1170 	 * variable's value is in the same format as the PATH envariable, i.e.
1171 	 * <directory>:<directory>:<directory>...
1172 	 */
1173 	if (Var_Exists("VPATH", VAR_CMD)) {
1174 		char *vpath, savec;
1175 		/*
1176 		 * GCC stores string constants in read-only memory, but
1177 		 * Var_Subst will want to write this thing, so store it
1178 		 * in an array
1179 		 */
1180 		static char VPATH[] = "${VPATH}";
1181 
1182 		vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
1183 		path = vpath;
1184 		do {
1185 			/* skip to end of directory */
1186 			for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1187 				continue;
1188 			/* Save terminator character so know when to stop */
1189 			savec = *cp;
1190 			*cp = '\0';
1191 			/* Add directory to search path */
1192 			(void)Dir_AddDir(dirSearchPath, path);
1193 			*cp = savec;
1194 			path = cp + 1;
1195 		} while (savec == ':');
1196 		free(vpath);
1197 	}
1198 
1199 	/*
1200 	 * Now that all search paths have been read for suffixes et al, it's
1201 	 * time to add the default search path to their lists...
1202 	 */
1203 	Suff_DoPaths();
1204 
1205 	/*
1206 	 * Propagate attributes through :: dependency lists.
1207 	 */
1208 	Targ_Propagate();
1209 
1210 	/* print the initial graph, if the user requested it */
1211 	if (DEBUG(GRAPH1))
1212 		Targ_PrintGraph(1);
1213 
1214 	/* print the values of any variables requested by the user */
1215 	if (printVars) {
1216 		LstNode ln;
1217 		Boolean expandVars;
1218 
1219 		if (debugVflag)
1220 			expandVars = FALSE;
1221 		else
1222 			expandVars = getBoolean(".MAKE.EXPAND_VARIABLES", FALSE);
1223 		for (ln = Lst_First(variables); ln != NULL;
1224 		    ln = Lst_Succ(ln)) {
1225 			char *var = (char *)Lst_Datum(ln);
1226 			char *value;
1227 
1228 			if (strchr(var, '$')) {
1229 				value = p1 = Var_Subst(NULL, var, VAR_GLOBAL, 0);
1230 			} else if (expandVars) {
1231 				char tmp[128];
1232 
1233 				if (snprintf(tmp, sizeof(tmp), "${%s}", var) >= (int)(sizeof(tmp)))
1234 					Fatal("%s: variable name too big: %s",
1235 					      progname, var);
1236 				value = p1 = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1237 			} else {
1238 				value = Var_Value(var, VAR_GLOBAL, &p1);
1239 			}
1240 			printf("%s\n", value ? value : "");
1241 			if (p1)
1242 				free(p1);
1243 		}
1244 	} else {
1245 		/*
1246 		 * Have now read the entire graph and need to make a list of
1247 		 * targets to create. If none was given on the command line,
1248 		 * we consult the parsing module to find the main target(s)
1249 		 * to create.
1250 		 */
1251 		if (Lst_IsEmpty(create))
1252 			targs = Parse_MainName();
1253 		else
1254 			targs = Targ_FindList(create, TARG_CREATE);
1255 
1256 		if (!compatMake) {
1257 			/*
1258 			 * Initialize job module before traversing the graph
1259 			 * now that any .BEGIN and .END targets have been read.
1260 			 * This is done only if the -q flag wasn't given
1261 			 * (to prevent the .BEGIN from being executed should
1262 			 * it exist).
1263 			 */
1264 			if (!queryFlag) {
1265 				Job_Init();
1266 				jobsRunning = TRUE;
1267 			}
1268 
1269 			/* Traverse the graph, checking on all the targets */
1270 			outOfDate = Make_Run(targs);
1271 		} else {
1272 			/*
1273 			 * Compat_Init will take care of creating all the
1274 			 * targets as well as initializing the module.
1275 			 */
1276 			Compat_Run(targs);
1277 		}
1278 	}
1279 
1280 #ifdef CLEANUP
1281 	Lst_Destroy(targs, NULL);
1282 	Lst_Destroy(variables, NULL);
1283 	Lst_Destroy(makefiles, NULL);
1284 	Lst_Destroy(create, (FreeProc *)free);
1285 #endif
1286 
1287 	/* print the graph now it's been processed if the user requested it */
1288 	if (DEBUG(GRAPH2))
1289 		Targ_PrintGraph(2);
1290 
1291 	Trace_Log(MAKEEND, 0);
1292 
1293 	Suff_End();
1294         Targ_End();
1295 	Arch_End();
1296 	Var_End();
1297 	Parse_End();
1298 	Dir_End();
1299 	Job_End();
1300 	Trace_End();
1301 
1302 	return outOfDate ? 1 : 0;
1303 }
1304 
1305 /*-
1306  * ReadMakefile  --
1307  *	Open and parse the given makefile.
1308  *
1309  * Results:
1310  *	0 if ok. -1 if couldn't open file.
1311  *
1312  * Side Effects:
1313  *	lots
1314  */
1315 static int
1316 ReadMakefile(const void *p, const void *q MAKE_ATTR_UNUSED)
1317 {
1318 	const char *fname = p;		/* makefile to read */
1319 	int fd;
1320 	size_t len = MAXPATHLEN;
1321 	char *name, *path = bmake_malloc(len);
1322 
1323 	if (!strcmp(fname, "-")) {
1324 		Parse_File(NULL /*stdin*/, -1);
1325 		Var_Set("MAKEFILE", "", VAR_GLOBAL, 0);
1326 	} else {
1327 		/* if we've chdir'd, rebuild the path name */
1328 		if (strcmp(curdir, objdir) && *fname != '/') {
1329 			size_t plen = strlen(curdir) + strlen(fname) + 2;
1330 			if (len < plen)
1331 				path = bmake_realloc(path, len = 2 * plen);
1332 
1333 			(void)snprintf(path, len, "%s/%s", curdir, fname);
1334 			fd = open(path, O_RDONLY);
1335 			if (fd != -1) {
1336 				fname = path;
1337 				goto found;
1338 			}
1339 
1340 			/* If curdir failed, try objdir (ala .depend) */
1341 			plen = strlen(objdir) + strlen(fname) + 2;
1342 			if (len < plen)
1343 				path = bmake_realloc(path, len = 2 * plen);
1344 			(void)snprintf(path, len, "%s/%s", objdir, fname);
1345 			fd = open(path, O_RDONLY);
1346 			if (fd != -1) {
1347 				fname = path;
1348 				goto found;
1349 			}
1350 		} else {
1351 			fd = open(fname, O_RDONLY);
1352 			if (fd != -1)
1353 				goto found;
1354 		}
1355 		/* look in -I and system include directories. */
1356 		name = Dir_FindFile(fname, parseIncPath);
1357 		if (!name)
1358 			name = Dir_FindFile(fname,
1359 				Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1360 		if (!name || (fd = open(name, O_RDONLY)) == -1) {
1361 			if (name)
1362 				free(name);
1363 			free(path);
1364 			return(-1);
1365 		}
1366 		fname = name;
1367 		/*
1368 		 * set the MAKEFILE variable desired by System V fans -- the
1369 		 * placement of the setting here means it gets set to the last
1370 		 * makefile specified, as it is set by SysV make.
1371 		 */
1372 found:
1373 		if (!doing_depend)
1374 			Var_Set("MAKEFILE", fname, VAR_GLOBAL, 0);
1375 		Parse_File(fname, fd);
1376 	}
1377 	free(path);
1378 	return(0);
1379 }
1380 
1381 
1382 
1383 /*-
1384  * Cmd_Exec --
1385  *	Execute the command in cmd, and return the output of that command
1386  *	in a string.
1387  *
1388  * Results:
1389  *	A string containing the output of the command, or the empty string
1390  *	If errnum is not NULL, it contains the reason for the command failure
1391  *
1392  * Side Effects:
1393  *	The string must be freed by the caller.
1394  */
1395 char *
1396 Cmd_Exec(const char *cmd, const char **errnum)
1397 {
1398     const char	*args[4];   	/* Args for invoking the shell */
1399     int 	fds[2];	    	/* Pipe streams */
1400     int 	cpid;	    	/* Child PID */
1401     int 	pid;	    	/* PID from wait() */
1402     char	*res;		/* result */
1403     int		status;		/* command exit status */
1404     Buffer	buf;		/* buffer to store the result */
1405     char	*cp;
1406     int		cc;
1407 
1408 
1409     *errnum = NULL;
1410 
1411     if (!shellName)
1412 	Shell_Init();
1413     /*
1414      * Set up arguments for shell
1415      */
1416     args[0] = shellName;
1417     args[1] = "-c";
1418     args[2] = cmd;
1419     args[3] = NULL;
1420 
1421     /*
1422      * Open a pipe for fetching its output
1423      */
1424     if (pipe(fds) == -1) {
1425 	*errnum = "Couldn't create pipe for \"%s\"";
1426 	goto bad;
1427     }
1428 
1429     /*
1430      * Fork
1431      */
1432     switch (cpid = vFork()) {
1433     case 0:
1434 	/*
1435 	 * Close input side of pipe
1436 	 */
1437 	(void)close(fds[0]);
1438 
1439 	/*
1440 	 * Duplicate the output stream to the shell's output, then
1441 	 * shut the extra thing down. Note we don't fetch the error
1442 	 * stream...why not? Why?
1443 	 */
1444 	(void)dup2(fds[1], 1);
1445 	(void)close(fds[1]);
1446 
1447 	Var_ExportVars();
1448 
1449 	(void)execv(shellPath, UNCONST(args));
1450 	_exit(1);
1451 	/*NOTREACHED*/
1452 
1453     case -1:
1454 	*errnum = "Couldn't exec \"%s\"";
1455 	goto bad;
1456 
1457     default:
1458 	/*
1459 	 * No need for the writing half
1460 	 */
1461 	(void)close(fds[1]);
1462 
1463 	Buf_Init(&buf, 0);
1464 
1465 	do {
1466 	    char   result[BUFSIZ];
1467 	    cc = read(fds[0], result, sizeof(result));
1468 	    if (cc > 0)
1469 		Buf_AddBytes(&buf, cc, result);
1470 	}
1471 	while (cc > 0 || (cc == -1 && errno == EINTR));
1472 
1473 	/*
1474 	 * Close the input side of the pipe.
1475 	 */
1476 	(void)close(fds[0]);
1477 
1478 	/*
1479 	 * Wait for the process to exit.
1480 	 */
1481 	while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) {
1482 	    JobReapChild(pid, status, FALSE);
1483 	    continue;
1484 	}
1485 	cc = Buf_Size(&buf);
1486 	res = Buf_Destroy(&buf, FALSE);
1487 
1488 	if (cc == 0)
1489 	    *errnum = "Couldn't read shell's output for \"%s\"";
1490 
1491 	if (WIFSIGNALED(status))
1492 	    *errnum = "\"%s\" exited on a signal";
1493 	else if (WEXITSTATUS(status) != 0)
1494 	    *errnum = "\"%s\" returned non-zero status";
1495 
1496 	/*
1497 	 * Null-terminate the result, convert newlines to spaces and
1498 	 * install it in the variable.
1499 	 */
1500 	res[cc] = '\0';
1501 	cp = &res[cc];
1502 
1503 	if (cc > 0 && *--cp == '\n') {
1504 	    /*
1505 	     * A final newline is just stripped
1506 	     */
1507 	    *cp-- = '\0';
1508 	}
1509 	while (cp >= res) {
1510 	    if (*cp == '\n') {
1511 		*cp = ' ';
1512 	    }
1513 	    cp--;
1514 	}
1515 	break;
1516     }
1517     return res;
1518 bad:
1519     res = bmake_malloc(1);
1520     *res = '\0';
1521     return res;
1522 }
1523 
1524 /*-
1525  * Error --
1526  *	Print an error message given its format.
1527  *
1528  * Results:
1529  *	None.
1530  *
1531  * Side Effects:
1532  *	The message is printed.
1533  */
1534 /* VARARGS */
1535 void
1536 Error(const char *fmt, ...)
1537 {
1538 	va_list ap;
1539 	FILE *err_file;
1540 
1541 	err_file = debug_file;
1542 	if (err_file == stdout)
1543 		err_file = stderr;
1544 	(void)fflush(stdout);
1545 	for (;;) {
1546 		va_start(ap, fmt);
1547 		fprintf(err_file, "%s: ", progname);
1548 		(void)vfprintf(err_file, fmt, ap);
1549 		va_end(ap);
1550 		(void)fprintf(err_file, "\n");
1551 		(void)fflush(err_file);
1552 		if (err_file == stderr)
1553 			break;
1554 		err_file = stderr;
1555 	}
1556 }
1557 
1558 /*-
1559  * Fatal --
1560  *	Produce a Fatal error message. If jobs are running, waits for them
1561  *	to finish.
1562  *
1563  * Results:
1564  *	None
1565  *
1566  * Side Effects:
1567  *	The program exits
1568  */
1569 /* VARARGS */
1570 void
1571 Fatal(const char *fmt, ...)
1572 {
1573 	va_list ap;
1574 
1575 	va_start(ap, fmt);
1576 	if (jobsRunning)
1577 		Job_Wait();
1578 
1579 	(void)fflush(stdout);
1580 	(void)vfprintf(stderr, fmt, ap);
1581 	va_end(ap);
1582 	(void)fprintf(stderr, "\n");
1583 	(void)fflush(stderr);
1584 
1585 	PrintOnError(NULL, NULL);
1586 
1587 	if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1588 		Targ_PrintGraph(2);
1589 	Trace_Log(MAKEERROR, 0);
1590 	exit(2);		/* Not 1 so -q can distinguish error */
1591 }
1592 
1593 /*
1594  * Punt --
1595  *	Major exception once jobs are being created. Kills all jobs, prints
1596  *	a message and exits.
1597  *
1598  * Results:
1599  *	None
1600  *
1601  * Side Effects:
1602  *	All children are killed indiscriminately and the program Lib_Exits
1603  */
1604 /* VARARGS */
1605 void
1606 Punt(const char *fmt, ...)
1607 {
1608 	va_list ap;
1609 
1610 	va_start(ap, fmt);
1611 	(void)fflush(stdout);
1612 	(void)fprintf(stderr, "%s: ", progname);
1613 	(void)vfprintf(stderr, fmt, ap);
1614 	va_end(ap);
1615 	(void)fprintf(stderr, "\n");
1616 	(void)fflush(stderr);
1617 
1618 	PrintOnError(NULL, NULL);
1619 
1620 	DieHorribly();
1621 }
1622 
1623 /*-
1624  * DieHorribly --
1625  *	Exit without giving a message.
1626  *
1627  * Results:
1628  *	None
1629  *
1630  * Side Effects:
1631  *	A big one...
1632  */
1633 void
1634 DieHorribly(void)
1635 {
1636 	if (jobsRunning)
1637 		Job_AbortAll();
1638 	if (DEBUG(GRAPH2))
1639 		Targ_PrintGraph(2);
1640 	Trace_Log(MAKEERROR, 0);
1641 	exit(2);		/* Not 1, so -q can distinguish error */
1642 }
1643 
1644 /*
1645  * Finish --
1646  *	Called when aborting due to errors in child shell to signal
1647  *	abnormal exit.
1648  *
1649  * Results:
1650  *	None
1651  *
1652  * Side Effects:
1653  *	The program exits
1654  */
1655 void
1656 Finish(int errors)
1657 	           	/* number of errors encountered in Make_Make */
1658 {
1659 	Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1660 }
1661 
1662 /*
1663  * enunlink --
1664  *	Remove a file carefully, avoiding directories.
1665  */
1666 int
1667 eunlink(const char *file)
1668 {
1669 	struct stat st;
1670 
1671 	if (lstat(file, &st) == -1)
1672 		return -1;
1673 
1674 	if (S_ISDIR(st.st_mode)) {
1675 		errno = EISDIR;
1676 		return -1;
1677 	}
1678 	return unlink(file);
1679 }
1680 
1681 /*
1682  * execError --
1683  *	Print why exec failed, avoiding stdio.
1684  */
1685 void
1686 execError(const char *af, const char *av)
1687 {
1688 #ifdef USE_IOVEC
1689 	int i = 0;
1690 	struct iovec iov[8];
1691 #define IOADD(s) \
1692 	(void)(iov[i].iov_base = UNCONST(s), \
1693 	    iov[i].iov_len = strlen(iov[i].iov_base), \
1694 	    i++)
1695 #else
1696 #define	IOADD(void)write(2, s, strlen(s))
1697 #endif
1698 
1699 	IOADD(progname);
1700 	IOADD(": ");
1701 	IOADD(af);
1702 	IOADD("(");
1703 	IOADD(av);
1704 	IOADD(") failed (");
1705 	IOADD(strerror(errno));
1706 	IOADD(")\n");
1707 
1708 #ifdef USE_IOVEC
1709 	while (writev(2, iov, 8) == -1 && errno == EAGAIN)
1710 	    continue;
1711 #endif
1712 }
1713 
1714 /*
1715  * usage --
1716  *	exit with usage message
1717  */
1718 static void
1719 usage(void)
1720 {
1721 	(void)fprintf(stderr,
1722 "usage: %s [-BeikNnqrstWX] \n\
1723             [-C directory] [-D variable] [-d flags] [-f makefile]\n\
1724             [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1725             [-V variable] [variable=value] [target ...]\n", progname);
1726 	exit(2);
1727 }
1728 
1729 
1730 int
1731 PrintAddr(void *a, void *b)
1732 {
1733     printf("%lx ", (unsigned long) a);
1734     return b ? 0 : 0;
1735 }
1736 
1737 
1738 
1739 void
1740 PrintOnError(GNode *gn, const char *s)
1741 {
1742     static GNode *en = NULL;
1743     char tmp[64];
1744     char *cp;
1745 
1746     if (s)
1747 	printf("%s", s);
1748 
1749     printf("\n%s: stopped in %s\n", progname, curdir);
1750 
1751     if (en)
1752 	return;				/* we've been here! */
1753     if (gn) {
1754 	/*
1755 	 * We can print this even if there is no .ERROR target.
1756 	 */
1757 	Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL, 0);
1758     }
1759     strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1760 	    sizeof(tmp) - 1);
1761     cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1762     if (cp) {
1763 	if (*cp)
1764 	    printf("%s", cp);
1765 	free(cp);
1766     }
1767     /*
1768      * Finally, see if there is a .ERROR target, and run it if so.
1769      */
1770     en = Targ_FindNode(".ERROR", TARG_NOCREATE);
1771     if (en) {
1772 	en->type |= OP_SPECIAL;
1773 	Compat_Make(en, en);
1774     }
1775 }
1776 
1777 void
1778 Main_ExportMAKEFLAGS(Boolean first)
1779 {
1780     static int once = 1;
1781     char tmp[64];
1782     char *s;
1783 
1784     if (once != first)
1785 	return;
1786     once = 0;
1787 
1788     strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1789 	    sizeof(tmp));
1790     s = Var_Subst(NULL, tmp, VAR_CMD, 0);
1791     if (s && *s) {
1792 #ifdef POSIX
1793 	setenv("MAKEFLAGS", s, 1);
1794 #else
1795 	setenv("MAKE", s, 1);
1796 #endif
1797     }
1798 }
1799 
1800 char *
1801 getTmpdir(void)
1802 {
1803     static char *tmpdir = NULL;
1804 
1805     if (!tmpdir) {
1806 	struct stat st;
1807 
1808 	/*
1809 	 * Honor $TMPDIR but only if it is valid.
1810 	 * Ensure it ends with /.
1811 	 */
1812 	tmpdir = Var_Subst(NULL, "${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL, 0);
1813 	if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
1814 	    free(tmpdir);
1815 	    tmpdir = bmake_strdup(_PATH_TMP);
1816 	}
1817     }
1818     return tmpdir;
1819 }
1820 
1821 /*
1822  * Create and open a temp file using "pattern".
1823  * If "fnamep" is provided set it to a copy of the filename created.
1824  * Otherwise unlink the file once open.
1825  */
1826 int
1827 mkTempFile(const char *pattern, char **fnamep)
1828 {
1829     static char *tmpdir = NULL;
1830     char tfile[MAXPATHLEN];
1831     int fd;
1832 
1833     if (!pattern)
1834 	pattern = TMPPAT;
1835     if (!tmpdir)
1836 	tmpdir = getTmpdir();
1837     if (pattern[0] == '/') {
1838 	snprintf(tfile, sizeof(tfile), "%s", pattern);
1839     } else {
1840 	snprintf(tfile, sizeof(tfile), "%s%s", tmpdir, pattern);
1841     }
1842     if ((fd = mkstemp(tfile)) < 0)
1843 	Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
1844     if (fnamep) {
1845 	*fnamep = bmake_strdup(tfile);
1846     } else {
1847 	unlink(tfile);			/* we just want the descriptor */
1848     }
1849     return fd;
1850 }
1851 
1852 
1853 /*
1854  * Return a Boolean based on setting of a knob.
1855  *
1856  * If the knob is not set, the supplied default is the return value.
1857  * If set, anything that looks or smells like "No", "False", "Off", "0" etc,
1858  * is FALSE, otherwise TRUE.
1859  */
1860 Boolean
1861 getBoolean(const char *name, Boolean bf)
1862 {
1863     char tmp[64];
1864     char *cp;
1865 
1866     if (snprintf(tmp, sizeof(tmp), "${%s:tl}", name) < (int)(sizeof(tmp))) {
1867 	cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1868 
1869 	if (cp) {
1870 	    switch(*cp) {
1871 	    case '\0':			/* not set - the default wins */
1872 		break;
1873 	    case '0':
1874 	    case 'f':
1875 	    case 'n':
1876 		bf = FALSE;
1877 		break;
1878 	    case 'o':
1879 		switch (cp[1]) {
1880 		case 'f':
1881 		    bf = FALSE;
1882 		    break;
1883 		default:
1884 		    bf = TRUE;
1885 		    break;
1886 		}
1887 		break;
1888 	    default:
1889 		bf = TRUE;
1890 		break;
1891 	    }
1892 	    free(cp);
1893 	}
1894     }
1895     return (bf);
1896 }
1897