xref: /netbsd-src/usr.bin/make/main.c (revision ae1bfcddc410612bc8c58b807e1830becb69a24c)
1 /*
2  * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
3  * Copyright (c) 1988, 1989 by Adam de Boor
4  * Copyright (c) 1989 by Berkeley Softworks
5  * 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. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38 
39 #ifndef lint
40 char copyright[] =
41 "@(#) Copyright (c) 1989 The Regents of the University of California.\n\
42  All rights reserved.\n";
43 #endif /* not lint */
44 
45 #ifndef lint
46 /* from: static char sccsid[] = "@(#)main.c	5.25 (Berkeley) 4/1/91"; */
47 static char *rcsid = "$Id: main.c,v 1.13 1994/03/05 00:34:53 cgd Exp $";
48 #endif /* not lint */
49 
50 /*-
51  * main.c --
52  *	The main file for this entire program. Exit routines etc
53  *	reside here.
54  *
55  * Utility functions defined in this file:
56  *	Main_ParseArgLine	Takes a line of arguments, breaks them and
57  *				treats them as if they were given when first
58  *				invoked. Used by the parse module to implement
59  *				the .MFLAGS target.
60  *
61  *	Error			Print a tagged error message. The global
62  *				MAKE variable must have been defined. This
63  *				takes a format string and two optional
64  *				arguments for it.
65  *
66  *	Fatal			Print an error message and exit. Also takes
67  *				a format string and two arguments.
68  *
69  *	Punt			Aborts all jobs and exits with a message. Also
70  *				takes a format string and two arguments.
71  *
72  *	Finish			Finish things up by printing the number of
73  *				errors which occured, as passed to it, and
74  *				exiting.
75  */
76 
77 #include <sys/types.h>
78 #include <sys/time.h>
79 #include <sys/param.h>
80 #include <sys/resource.h>
81 #include <sys/signal.h>
82 #include <sys/stat.h>
83 #include <errno.h>
84 #include <fcntl.h>
85 #include <stdio.h>
86 #if __STDC__
87 #include <stdarg.h>
88 #else
89 #include <varargs.h>
90 #endif
91 #include "make.h"
92 #include "hash.h"
93 #include "dir.h"
94 #include "job.h"
95 #include "pathnames.h"
96 
97 #ifndef	DEFMAXLOCAL
98 #define	DEFMAXLOCAL DEFMAXJOBS
99 #endif	DEFMAXLOCAL
100 
101 #define	MAKEFLAGS	".MAKEFLAGS"
102 
103 Lst			create;		/* Targets to be made */
104 time_t			now;		/* Time at start of make */
105 GNode			*DEFAULT;	/* .DEFAULT node */
106 Boolean			allPrecious;	/* .PRECIOUS given on line by itself */
107 
108 static Boolean		noBuiltins;	/* -r flag */
109 static Lst		makefiles;	/* ordered list of makefiles to read */
110 int			maxJobs;	/* -J argument */
111 static int		maxLocal;	/* -L argument */
112 Boolean			compatMake;	/* -B argument */
113 Boolean			debug;		/* -d flag */
114 Boolean			noExecute;	/* -n flag */
115 Boolean			keepgoing;	/* -k flag */
116 Boolean			queryFlag;	/* -q flag */
117 Boolean			touchFlag;	/* -t flag */
118 Boolean			usePipes;	/* !-P flag */
119 Boolean			ignoreErrors;	/* -i flag */
120 Boolean			beSilent;	/* -s flag */
121 Boolean			oldVars;	/* variable substitution style */
122 Boolean			checkEnvFirst;	/* -e flag */
123 static Boolean		jobsRunning;	/* TRUE if the jobs might be running */
124 
125 static Boolean		ReadMakefile();
126 static void		usage();
127 
128 static char *curdir;			/* startup directory */
129 static char *objdir;			/* where we chdir'ed to */
130 
131 /*-
132  * MainParseArgs --
133  *	Parse a given argument vector. Called from main() and from
134  *	Main_ParseArgLine() when the .MAKEFLAGS target is used.
135  *
136  *	XXX: Deal with command line overriding .MAKEFLAGS in makefile
137  *
138  * Results:
139  *	None
140  *
141  * Side Effects:
142  *	Various global and local flags will be set depending on the flags
143  *	given
144  */
145 static void
146 MainParseArgs(argc, argv)
147 	int argc;
148 	char **argv;
149 {
150 	extern int optind;
151 	extern char *optarg;
152 	char c;
153 
154 	optind = 1;	/* since we're called more than once */
155 #ifdef notyet
156 # define OPTFLAGS "BD:I:L:PSd:ef:ij:knqrst"
157 #else
158 # define OPTFLAGS "D:I:d:ef:ij:knqrst"
159 #endif
160 rearg:	while((c = getopt(argc, argv, OPTFLAGS)) != EOF) {
161 		switch(c) {
162 		case 'D':
163 			Var_Set(optarg, "1", VAR_GLOBAL);
164 			Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
165 			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
166 			break;
167 		case 'I':
168 			Parse_AddIncludeDir(optarg);
169 			Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
170 			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
171 			break;
172 #ifdef notyet
173 		case 'B':
174 			compatMake = TRUE;
175 			break;
176 		case 'L':
177 			maxLocal = atoi(optarg);
178 			Var_Append(MAKEFLAGS, "-L", VAR_GLOBAL);
179 			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
180 			break;
181 		case 'P':
182 			usePipes = FALSE;
183 			Var_Append(MAKEFLAGS, "-P", VAR_GLOBAL);
184 			break;
185 		case 'S':
186 			keepgoing = FALSE;
187 			Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
188 			break;
189 #endif
190 		case 'd': {
191 			char *modules = optarg;
192 
193 			for (; *modules; ++modules)
194 				switch (*modules) {
195 				case 'A':
196 					debug = ~0;
197 					break;
198 				case 'a':
199 					debug |= DEBUG_ARCH;
200 					break;
201 				case 'c':
202 					debug |= DEBUG_COND;
203 					break;
204 				case 'd':
205 					debug |= DEBUG_DIR;
206 					break;
207 				case 'f':
208 					debug |= DEBUG_FOR;
209 					break;
210 				case 'g':
211 					if (modules[1] == '1') {
212 						debug |= DEBUG_GRAPH1;
213 						++modules;
214 					}
215 					else if (modules[1] == '2') {
216 						debug |= DEBUG_GRAPH2;
217 						++modules;
218 					}
219 					break;
220 				case 'j':
221 					debug |= DEBUG_JOB;
222 					break;
223 				case 'm':
224 					debug |= DEBUG_MAKE;
225 					break;
226 				case 's':
227 					debug |= DEBUG_SUFF;
228 					break;
229 				case 't':
230 					debug |= DEBUG_TARG;
231 					break;
232 				case 'v':
233 					debug |= DEBUG_VAR;
234 					break;
235 				default:
236 					(void)fprintf(stderr,
237 				"make: illegal argument to d option -- %c\n",
238 					    *modules);
239 					usage();
240 				}
241 			Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
242 			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
243 			break;
244 		}
245 		case 'e':
246 			checkEnvFirst = TRUE;
247 			Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
248 			break;
249 		case 'f':
250 			(void)Lst_AtEnd(makefiles, (ClientData)optarg);
251 			break;
252 		case 'i':
253 			ignoreErrors = TRUE;
254 			Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
255 			break;
256 		case 'j':
257 			maxJobs = atoi(optarg);
258 			Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
259 			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
260 			break;
261 		case 'k':
262 			keepgoing = TRUE;
263 			Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
264 			break;
265 		case 'n':
266 			noExecute = TRUE;
267 			Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
268 			break;
269 		case 'q':
270 			queryFlag = TRUE;
271 			/* Kind of nonsensical, wot? */
272 			Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
273 			break;
274 		case 'r':
275 			noBuiltins = TRUE;
276 			Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
277 			break;
278 		case 's':
279 			beSilent = TRUE;
280 			Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
281 			break;
282 		case 't':
283 			touchFlag = TRUE;
284 			Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
285 			break;
286 		default:
287 		case '?':
288 			usage();
289 		}
290 	}
291 
292 	oldVars = TRUE;
293 
294 	/*
295 	 * See if the rest of the arguments are variable assignments and
296 	 * perform them if so. Else take them to be targets and stuff them
297 	 * on the end of the "create" list.
298 	 */
299 	for (argv += optind, argc -= optind; *argv; ++argv, --argc)
300 		if (Parse_IsVar(*argv))
301 			Parse_DoVar(*argv, VAR_CMD);
302 		else {
303 			if (!**argv)
304 				Punt("illegal (null) argument.");
305 			if (**argv == '-') {
306 				if ((*argv)[1])
307 					optind = 0;     /* -flag... */
308 				else
309 					optind = 1;     /* - */
310 				goto rearg;
311 			}
312 			(void)Lst_AtEnd(create, (ClientData)*argv);
313 		}
314 }
315 
316 /*-
317  * Main_ParseArgLine --
318  *  	Used by the parse module when a .MFLAGS or .MAKEFLAGS target
319  *	is encountered and by main() when reading the .MAKEFLAGS envariable.
320  *	Takes a line of arguments and breaks it into its
321  * 	component words and passes those words and the number of them to the
322  *	MainParseArgs function.
323  *	The line should have all its leading whitespace removed.
324  *
325  * Results:
326  *	None
327  *
328  * Side Effects:
329  *	Only those that come from the various arguments.
330  */
331 void
332 Main_ParseArgLine(line)
333 	char *line;			/* Line to fracture */
334 {
335 	char **argv;			/* Manufactured argument vector */
336 	int argc;			/* Number of arguments in argv */
337 
338 	if (line == NULL)
339 		return;
340 	for (; *line == ' '; ++line)
341 		continue;
342 	if (!*line)
343 		return;
344 
345 	argv = brk_string(line, &argc);
346 	MainParseArgs(argc, argv);
347 }
348 
349 /*-
350  * main --
351  *	The main function, for obvious reasons. Initializes variables
352  *	and a few modules, then parses the arguments give it in the
353  *	environment and on the command line. Reads the system makefile
354  *	followed by either Makefile, makefile or the file given by the
355  *	-f argument. Sets the .MAKEFLAGS PMake variable based on all the
356  *	flags it has received by then uses either the Make or the Compat
357  *	module to create the initial list of targets.
358  *
359  * Results:
360  *	If -q was given, exits -1 if anything was out-of-date. Else it exits
361  *	0.
362  *
363  * Side Effects:
364  *	The program exits when done. Targets are created. etc. etc. etc.
365  */
366 int
367 main(argc, argv)
368 	int argc;
369 	char **argv;
370 {
371 	Lst targs;	/* target nodes to create -- passed to Make_Init */
372 	Boolean outOfDate = TRUE; 	/* FALSE if all targets up to date */
373 	struct stat sb, sa;
374 	char *p, *path, *pwd, *getenv(), *getwd();
375 	char mdpath[MAXPATHLEN + 1];
376 	char obpath[MAXPATHLEN + 1];
377 	char cdpath[MAXPATHLEN + 1];
378 
379 	/*
380 	 * Find where we are and take care of PWD for the automounter...
381 	 * All this code is so that we know where we are when we start up
382 	 * on a different machine with pmake.
383 	 */
384 	curdir = cdpath;
385 	if (getwd(curdir) == NULL) {
386 		(void)fprintf(stderr, "make: %s.\n", curdir);
387 		exit(2);
388 	}
389 
390 	if (stat(curdir, &sa) == -1) {
391 	    (void)fprintf(stderr, "make: %s: %s.\n",
392 			  curdir, strerror(errno));
393 	    exit(2);
394 	}
395 
396 	if ((pwd = getenv("PWD")) != NULL) {
397 	    if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
398 		sa.st_dev == sb.st_dev)
399 		(void) strcpy(curdir, pwd);
400 	}
401 
402 
403 	/*
404 	 * if the MAKEOBJDIR (or by default, the _PATH_OBJDIR) directory
405 	 * exists, change into it and build there.  Once things are
406 	 * initted, have to add the original directory to the search path,
407 	 * and modify the paths for the Makefiles apropriately.  The
408 	 * current directory is also placed as a variable for make scripts.
409 	 */
410 	if (!(path = getenv("MAKEOBJDIR"))) {
411 		path = _PATH_OBJDIR;
412 		(void) sprintf(mdpath, "%s.%s", path, MACHINE);
413 	}
414 	else
415 		(void) strncpy(mdpath, path, MAXPATHLEN + 1);
416 
417 	if (stat(mdpath, &sb) == 0 && S_ISDIR(sb.st_mode)) {
418 
419 		if (chdir(mdpath)) {
420 			(void)fprintf(stderr, "make warning: %s: %s.\n",
421 				      mdpath, strerror(errno));
422 			objdir = curdir;
423 		}
424 		else {
425 			if (mdpath[0] != '/') {
426 				(void) sprintf(obpath, "%s/%s", curdir, mdpath);
427 				objdir = obpath;
428 			}
429 			else
430 				objdir = mdpath;
431 		}
432 	}
433 	else {
434 		if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
435 
436 			if (chdir(path)) {
437 				(void)fprintf(stderr, "make warning: %s: %s.\n",
438 					      path, strerror(errno));
439 				objdir = curdir;
440 			}
441 			else {
442 				if (path[0] != '/') {
443 					(void) sprintf(obpath, "%s/%s", curdir,
444 						       path);
445 					objdir = obpath;
446 				}
447 				else
448 					objdir = obpath;
449 			}
450 		}
451 		else
452 			objdir = curdir;
453 	}
454 
455 	setenv("PWD", objdir, 1);
456 
457 	create = Lst_Init(FALSE);
458 	makefiles = Lst_Init(FALSE);
459 	beSilent = FALSE;		/* Print commands as executed */
460 	ignoreErrors = FALSE;		/* Pay attention to non-zero returns */
461 	noExecute = FALSE;		/* Execute all commands */
462 	keepgoing = FALSE;		/* Stop on error */
463 	allPrecious = FALSE;		/* Remove targets when interrupted */
464 	queryFlag = FALSE;		/* This is not just a check-run */
465 	noBuiltins = FALSE;		/* Read the built-in rules */
466 	touchFlag = FALSE;		/* Actually update targets */
467 	usePipes = TRUE;		/* Catch child output in pipes */
468 	debug = 0;			/* No debug verbosity, please. */
469 	jobsRunning = FALSE;
470 
471 	maxJobs = DEFMAXJOBS;		/* Set default max concurrency */
472 	maxLocal = DEFMAXLOCAL;		/* Set default local max concurrency */
473 #ifdef notyet
474 	compatMake = FALSE;		/* No compat mode */
475 #else
476 	compatMake = TRUE;		/* No compat mode */
477 #endif
478 
479 
480 	/*
481 	 * Initialize the parsing, directory and variable modules to prepare
482 	 * for the reading of inclusion paths and variable settings on the
483 	 * command line
484 	 */
485 	Dir_Init();		/* Initialize directory structures so -I flags
486 				 * can be processed correctly */
487 	Parse_Init();		/* Need to initialize the paths of #include
488 				 * directories */
489 	Var_Init();		/* As well as the lists of variables for
490 				 * parsing arguments */
491 	if (objdir != curdir)
492 		Dir_AddDir(dirSearchPath, curdir);
493 	Var_Set(".CURDIR", curdir, VAR_GLOBAL);
494 	Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
495 
496 	/*
497 	 * Initialize various variables.
498 	 *	MAKE also gets this name, for compatibility
499 	 *	.MAKEFLAGS gets set to the empty string just in case.
500 	 *	MFLAGS also gets initialized empty, for compatibility.
501 	 */
502 	Var_Set("MAKE", argv[0], VAR_GLOBAL);
503 	Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
504 	Var_Set("MFLAGS", "", VAR_GLOBAL);
505 #ifdef MACHINE
506 	Var_Set("MACHINE", MACHINE, VAR_GLOBAL);
507 #endif
508 #ifdef MACHINE_ARCH
509 	Var_Set("MACHINE_ARCH", MACHINE_ARCH, VAR_GLOBAL);
510 #endif
511 
512 	/*
513 	 * First snag any flags out of the MAKE environment variable.
514 	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
515 	 * in a different format).
516 	 */
517 #ifdef POSIX
518 	Main_ParseArgLine(getenv("MAKEFLAGS"));
519 #else
520 	Main_ParseArgLine(getenv("MAKE"));
521 #endif
522 
523 	MainParseArgs(argc, argv);
524 
525 	/*
526 	 * Initialize archive, target and suffix modules in preparation for
527 	 * parsing the makefile(s)
528 	 */
529 	Arch_Init();
530 	Targ_Init();
531 	Suff_Init();
532 
533 	DEFAULT = NILGNODE;
534 	(void)time(&now);
535 
536 	/*
537 	 * Set up the .TARGETS variable to contain the list of targets to be
538 	 * created. If none specified, make the variable empty -- the parser
539 	 * will fill the thing in with the default or .MAIN target.
540 	 */
541 	if (!Lst_IsEmpty(create)) {
542 		LstNode ln;
543 
544 		for (ln = Lst_First(create); ln != NILLNODE;
545 		    ln = Lst_Succ(ln)) {
546 			char *name = (char *)Lst_Datum(ln);
547 
548 			Var_Append(".TARGETS", name, VAR_GLOBAL);
549 		}
550 	} else
551 		Var_Set(".TARGETS", "", VAR_GLOBAL);
552 
553 	/*
554 	 * Read in the built-in rules first, followed by the specified makefile,
555 	 * if it was (makefile != (char *) NULL), or the default Makefile and
556 	 * makefile, in that order, if it wasn't.
557 	 */
558 	 if (!noBuiltins && !ReadMakefile(_PATH_DEFSYSMK))
559 		Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
560 
561 	if (!Lst_IsEmpty(makefiles)) {
562 		LstNode ln;
563 
564 		ln = Lst_Find(makefiles, (ClientData)NULL, ReadMakefile);
565 		if (ln != NILLNODE)
566 			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
567 	} else if (!ReadMakefile("makefile"))
568 		(void)ReadMakefile("Makefile");
569 
570 	(void)ReadMakefile(".depend");
571 
572 	Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL), VAR_GLOBAL);
573 
574 	/* Install all the flags into the MAKE envariable. */
575 	if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL)) != NULL) && *p)
576 #ifdef POSIX
577 		setenv("MAKEFLAGS", p, 1);
578 #else
579 		setenv("MAKE", p, 1);
580 #endif
581 
582 	/*
583 	 * For compatibility, look at the directories in the VPATH variable
584 	 * and add them to the search path, if the variable is defined. The
585 	 * variable's value is in the same format as the PATH envariable, i.e.
586 	 * <directory>:<directory>:<directory>...
587 	 */
588 	if (Var_Exists("VPATH", VAR_CMD)) {
589 		char *vpath, *path, *cp, savec;
590 		/*
591 		 * GCC stores string constants in read-only memory, but
592 		 * Var_Subst will want to write this thing, so store it
593 		 * in an array
594 		 */
595 		static char VPATH[] = "${VPATH}";
596 
597 		vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
598 		path = vpath;
599 		do {
600 			/* skip to end of directory */
601 			for (cp = path; *cp != ':' && *cp != '\0'; cp++)
602 				continue;
603 			/* Save terminator character so know when to stop */
604 			savec = *cp;
605 			*cp = '\0';
606 			/* Add directory to search path */
607 			Dir_AddDir(dirSearchPath, path);
608 			*cp = savec;
609 			path = cp + 1;
610 		} while (savec == ':');
611 		(void)free((Address)vpath);
612 	}
613 
614 	/*
615 	 * Now that all search paths have been read for suffixes et al, it's
616 	 * time to add the default search path to their lists...
617 	 */
618 	Suff_DoPaths();
619 
620 	/* print the initial graph, if the user requested it */
621 	if (DEBUG(GRAPH1))
622 		Targ_PrintGraph(1);
623 
624 	/*
625 	 * Have now read the entire graph and need to make a list of targets
626 	 * to create. If none was given on the command line, we consult the
627 	 * parsing module to find the main target(s) to create.
628 	 */
629 	if (Lst_IsEmpty(create))
630 		targs = Parse_MainName();
631 	else
632 		targs = Targ_FindList(create, TARG_CREATE);
633 
634 /*
635  * this was original amMake -- want to allow parallelism, so put this
636  * back in, eventually.
637  */
638 	if (!compatMake) {
639 		/*
640 		 * Initialize job module before traversing the graph, now that
641 		 * any .BEGIN and .END targets have been read.  This is done
642 		 * only if the -q flag wasn't given (to prevent the .BEGIN from
643 		 * being executed should it exist).
644 		 */
645 		if (!queryFlag) {
646 			if (maxLocal == -1)
647 				maxLocal = maxJobs;
648 			Job_Init(maxJobs, maxLocal);
649 			jobsRunning = TRUE;
650 		}
651 
652 		/* Traverse the graph, checking on all the targets */
653 		outOfDate = Make_Run(targs);
654 	} else
655 		/*
656 		 * Compat_Init will take care of creating all the targets as
657 		 * well as initializing the module.
658 		 */
659 		Compat_Run(targs);
660 
661 	/* print the graph now it's been processed if the user requested it */
662 	if (DEBUG(GRAPH2))
663 		Targ_PrintGraph(2);
664 
665 	if (queryFlag && outOfDate)
666 		return(1);
667 	else
668 		return(0);
669 }
670 
671 /*-
672  * ReadMakefile  --
673  *	Open and parse the given makefile.
674  *
675  * Results:
676  *	TRUE if ok. FALSE if couldn't open file.
677  *
678  * Side Effects:
679  *	lots
680  */
681 static Boolean
682 ReadMakefile(fname)
683 	char *fname;		/* makefile to read */
684 {
685 	extern Lst parseIncPath, sysIncPath;
686 	FILE *stream;
687 	char *name, path[MAXPATHLEN + 1];
688 
689 	if (!strcmp(fname, "-")) {
690 		Parse_File("(stdin)", stdin);
691 		Var_Set("MAKEFILE", "", VAR_GLOBAL);
692 	} else {
693 		if ((stream = fopen(fname, "r")) != NULL)
694 			goto found;
695 		/* if we've chdir'd, rebuild the path name */
696 		if (curdir != objdir && *fname != '/') {
697 			(void)sprintf(path, "%s/%s", curdir, fname);
698 			if ((stream = fopen(path, "r")) != NULL) {
699 				fname = path;
700 				goto found;
701 			}
702 		}
703 		/* look in -I and system include directories. */
704 		name = Dir_FindFile(fname, parseIncPath);
705 		if (!name)
706 			name = Dir_FindFile(fname, sysIncPath);
707 		if (!name || !(stream = fopen(name, "r")))
708 			return(FALSE);
709 		fname = name;
710 		/*
711 		 * set the MAKEFILE variable desired by System V fans -- the
712 		 * placement of the setting here means it gets set to the last
713 		 * makefile specified, as it is set by SysV make.
714 		 */
715 found:		Var_Set("MAKEFILE", fname, VAR_GLOBAL);
716 		Parse_File(fname, stream);
717 		(void)fclose(stream);
718 	}
719 	return(TRUE);
720 }
721 
722 /*-
723  * Error --
724  *	Print an error message given its format.
725  *
726  * Results:
727  *	None.
728  *
729  * Side Effects:
730  *	The message is printed.
731  */
732 /* VARARGS */
733 void
734 #if __STDC__
735 Error(char *fmt, ...)
736 #else
737 Error(va_alist)
738 	va_dcl
739 #endif
740 {
741 	va_list ap;
742 #if __STDC__
743 	va_start(ap, fmt);
744 #else
745 	char *fmt;
746 
747 	va_start(ap);
748 	fmt = va_arg(ap, char *);
749 #endif
750 	(void)vfprintf(stderr, fmt, ap);
751 	va_end(ap);
752 	(void)fprintf(stderr, "\n");
753 	(void)fflush(stderr);
754 }
755 
756 /*-
757  * Fatal --
758  *	Produce a Fatal error message. If jobs are running, waits for them
759  *	to finish.
760  *
761  * Results:
762  *	None
763  *
764  * Side Effects:
765  *	The program exits
766  */
767 /* VARARGS */
768 void
769 #if __STDC__
770 Fatal(char *fmt, ...)
771 #else
772 Fatal(va_alist)
773 	va_dcl
774 #endif
775 {
776 	va_list ap;
777 #if __STDC__
778 	va_start(ap, fmt);
779 #else
780 	char *fmt;
781 
782 	va_start(ap);
783 	fmt = va_arg(ap, char *);
784 #endif
785 	if (jobsRunning)
786 		Job_Wait();
787 
788 	(void)vfprintf(stderr, fmt, ap);
789 	va_end(ap);
790 	(void)fprintf(stderr, "\n");
791 	(void)fflush(stderr);
792 
793 	if (DEBUG(GRAPH2))
794 		Targ_PrintGraph(2);
795 	exit(2);		/* Not 1 so -q can distinguish error */
796 }
797 
798 /*
799  * Punt --
800  *	Major exception once jobs are being created. Kills all jobs, prints
801  *	a message and exits.
802  *
803  * Results:
804  *	None
805  *
806  * Side Effects:
807  *	All children are killed indiscriminately and the program Lib_Exits
808  */
809 /* VARARGS */
810 void
811 #if __STDC__
812 Punt(char *fmt, ...)
813 #else
814 Punt(va_alist)
815 	va_dcl
816 #endif
817 {
818 	va_list ap;
819 #if __STDC__
820 	va_start(ap, fmt);
821 #else
822 	char *fmt;
823 
824 	va_start(ap);
825 	fmt = va_arg(ap, char *);
826 #endif
827 
828 	(void)fprintf(stderr, "make: ");
829 	(void)vfprintf(stderr, fmt, ap);
830 	va_end(ap);
831 	(void)fprintf(stderr, "\n");
832 	(void)fflush(stderr);
833 
834 	DieHorribly();
835 }
836 
837 /*-
838  * DieHorribly --
839  *	Exit without giving a message.
840  *
841  * Results:
842  *	None
843  *
844  * Side Effects:
845  *	A big one...
846  */
847 void
848 DieHorribly()
849 {
850 	if (jobsRunning)
851 		Job_AbortAll();
852 	if (DEBUG(GRAPH2))
853 		Targ_PrintGraph(2);
854 	exit(2);		/* Not 1, so -q can distinguish error */
855 }
856 
857 /*
858  * Finish --
859  *	Called when aborting due to errors in child shell to signal
860  *	abnormal exit.
861  *
862  * Results:
863  *	None
864  *
865  * Side Effects:
866  *	The program exits
867  */
868 void
869 Finish(errors)
870 	int errors;	/* number of errors encountered in Make_Make */
871 {
872 	Fatal("%d error%s", errors, errors == 1 ? "" : "s");
873 }
874 
875 /*
876  * emalloc --
877  *	malloc, but die on error.
878  */
879 char *
880 emalloc(len)
881 	u_int len;
882 {
883 	char *p;
884 
885 	if (!(p = malloc(len)))
886 		enomem();
887 	return(p);
888 }
889 
890 /*
891  * enomem --
892  *	die when out of memory.
893  */
894 void
895 enomem()
896 {
897 	(void)fprintf(stderr, "make: %s.\n", strerror(errno));
898 	exit(2);
899 }
900 
901 /*
902  * usage --
903  *	exit with usage message
904  */
905 static void
906 usage()
907 {
908 	(void)fprintf(stderr,
909 "usage: make [-eiknqrst] [-D variable] [-d flags] [-f makefile ]\n\
910             [-I directory] [-j max_jobs] [variable=value]\n");
911 	exit(2);
912 }
913