xref: /netbsd-src/usr.bin/make/main.c (revision d9158b13b5dfe46201430699a3f7a235ecf28df3)
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.15 1994/06/16 18:50:13 jtc 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)strdup(*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, TRUE);
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, *p1, *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         str_init();
492 	if (objdir != curdir)
493 		Dir_AddDir(dirSearchPath, curdir);
494 	Var_Set(".CURDIR", curdir, VAR_GLOBAL);
495 	Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
496 
497 	/*
498 	 * Initialize various variables.
499 	 *	MAKE also gets this name, for compatibility
500 	 *	.MAKEFLAGS gets set to the empty string just in case.
501 	 *	MFLAGS also gets initialized empty, for compatibility.
502 	 */
503 	Var_Set("MAKE", argv[0], VAR_GLOBAL);
504 	Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
505 	Var_Set("MFLAGS", "", VAR_GLOBAL);
506 #ifdef MACHINE
507 	Var_Set("MACHINE", MACHINE, VAR_GLOBAL);
508 #endif
509 #ifdef MACHINE_ARCH
510 	Var_Set("MACHINE_ARCH", MACHINE_ARCH, VAR_GLOBAL);
511 #endif
512 
513 	/*
514 	 * First snag any flags out of the MAKE environment variable.
515 	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
516 	 * in a different format).
517 	 */
518 #ifdef POSIX
519 	Main_ParseArgLine(getenv("MAKEFLAGS"));
520 #else
521 	Main_ParseArgLine(getenv("MAKE"));
522 #endif
523 
524 	MainParseArgs(argc, argv);
525 
526 	/*
527 	 * Initialize archive, target and suffix modules in preparation for
528 	 * parsing the makefile(s)
529 	 */
530 	Arch_Init();
531 	Targ_Init();
532 	Suff_Init();
533 
534 	DEFAULT = NILGNODE;
535 	(void)time(&now);
536 
537 	/*
538 	 * Set up the .TARGETS variable to contain the list of targets to be
539 	 * created. If none specified, make the variable empty -- the parser
540 	 * will fill the thing in with the default or .MAIN target.
541 	 */
542 	if (!Lst_IsEmpty(create)) {
543 		LstNode ln;
544 
545 		for (ln = Lst_First(create); ln != NILLNODE;
546 		    ln = Lst_Succ(ln)) {
547 			char *name = (char *)Lst_Datum(ln);
548 
549 			Var_Append(".TARGETS", name, VAR_GLOBAL);
550 		}
551 	} else
552 		Var_Set(".TARGETS", "", VAR_GLOBAL);
553 
554 	/*
555 	 * Read in the built-in rules first, followed by the specified makefile,
556 	 * if it was (makefile != (char *) NULL), or the default Makefile and
557 	 * makefile, in that order, if it wasn't.
558 	 */
559 	 if (!noBuiltins && !ReadMakefile(_PATH_DEFSYSMK))
560 		Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
561 
562 	if (!Lst_IsEmpty(makefiles)) {
563 		LstNode ln;
564 
565 		ln = Lst_Find(makefiles, (ClientData)NULL, ReadMakefile);
566 		if (ln != NILLNODE)
567 			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
568 	} else if (!ReadMakefile("makefile"))
569 		(void)ReadMakefile("Makefile");
570 
571 	(void)ReadMakefile(".depend");
572 
573 	Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
574 	if (p1)
575 	    free(p1);
576 
577 	/* Install all the flags into the MAKE envariable. */
578 	if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
579 #ifdef POSIX
580 		setenv("MAKEFLAGS", p, 1);
581 #else
582 		setenv("MAKE", p, 1);
583 #endif
584 	if (p1)
585 	    free(p1);
586 
587 	/*
588 	 * For compatibility, look at the directories in the VPATH variable
589 	 * and add them to the search path, if the variable is defined. The
590 	 * variable's value is in the same format as the PATH envariable, i.e.
591 	 * <directory>:<directory>:<directory>...
592 	 */
593 	if (Var_Exists("VPATH", VAR_CMD)) {
594 		char *vpath, *path, *cp, savec;
595 		/*
596 		 * GCC stores string constants in read-only memory, but
597 		 * Var_Subst will want to write this thing, so store it
598 		 * in an array
599 		 */
600 		static char VPATH[] = "${VPATH}";
601 
602 		vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
603 		path = vpath;
604 		do {
605 			/* skip to end of directory */
606 			for (cp = path; *cp != ':' && *cp != '\0'; cp++)
607 				continue;
608 			/* Save terminator character so know when to stop */
609 			savec = *cp;
610 			*cp = '\0';
611 			/* Add directory to search path */
612 			Dir_AddDir(dirSearchPath, path);
613 			*cp = savec;
614 			path = cp + 1;
615 		} while (savec == ':');
616 		(void)free((Address)vpath);
617 	}
618 
619 	/*
620 	 * Now that all search paths have been read for suffixes et al, it's
621 	 * time to add the default search path to their lists...
622 	 */
623 	Suff_DoPaths();
624 
625 	/* print the initial graph, if the user requested it */
626 	if (DEBUG(GRAPH1))
627 		Targ_PrintGraph(1);
628 
629 	/*
630 	 * Have now read the entire graph and need to make a list of targets
631 	 * to create. If none was given on the command line, we consult the
632 	 * parsing module to find the main target(s) to create.
633 	 */
634 	if (Lst_IsEmpty(create))
635 		targs = Parse_MainName();
636 	else
637 		targs = Targ_FindList(create, TARG_CREATE);
638 
639 /*
640  * this was original amMake -- want to allow parallelism, so put this
641  * back in, eventually.
642  */
643 	if (!compatMake) {
644 		/*
645 		 * Initialize job module before traversing the graph, now that
646 		 * any .BEGIN and .END targets have been read.  This is done
647 		 * only if the -q flag wasn't given (to prevent the .BEGIN from
648 		 * being executed should it exist).
649 		 */
650 		if (!queryFlag) {
651 			if (maxLocal == -1)
652 				maxLocal = maxJobs;
653 			Job_Init(maxJobs, maxLocal);
654 			jobsRunning = TRUE;
655 		}
656 
657 		/* Traverse the graph, checking on all the targets */
658 		outOfDate = Make_Run(targs);
659 	} else
660 		/*
661 		 * Compat_Init will take care of creating all the targets as
662 		 * well as initializing the module.
663 		 */
664 		Compat_Run(targs);
665 
666 	Lst_Destroy(targs, NOFREE);
667 	Lst_Destroy(makefiles, NOFREE);
668 	Lst_Destroy(create, (void (*) __P((ClientData))) free);
669 
670 	/* print the graph now it's been processed if the user requested it */
671 	if (DEBUG(GRAPH2))
672 		Targ_PrintGraph(2);
673 
674 	Suff_End();
675         Targ_End();
676 	Arch_End();
677 	str_end();
678 	Var_End();
679 	Parse_End();
680 	Dir_End();
681 
682 	if (queryFlag && outOfDate)
683 		return(1);
684 	else
685 		return(0);
686 }
687 
688 /*-
689  * ReadMakefile  --
690  *	Open and parse the given makefile.
691  *
692  * Results:
693  *	TRUE if ok. FALSE if couldn't open file.
694  *
695  * Side Effects:
696  *	lots
697  */
698 static Boolean
699 ReadMakefile(fname)
700 	char *fname;		/* makefile to read */
701 {
702 	extern Lst parseIncPath, sysIncPath;
703 	FILE *stream;
704 	char *name, path[MAXPATHLEN + 1];
705 
706 	if (!strcmp(fname, "-")) {
707 		Parse_File("(stdin)", stdin);
708 		Var_Set("MAKEFILE", "", VAR_GLOBAL);
709 	} else {
710 		if ((stream = fopen(fname, "r")) != NULL)
711 			goto found;
712 		/* if we've chdir'd, rebuild the path name */
713 		if (curdir != objdir && *fname != '/') {
714 			(void)sprintf(path, "%s/%s", curdir, fname);
715 			if ((stream = fopen(path, "r")) != NULL) {
716 				fname = path;
717 				goto found;
718 			}
719 		}
720 		/* look in -I and system include directories. */
721 		name = Dir_FindFile(fname, parseIncPath);
722 		if (!name)
723 			name = Dir_FindFile(fname, sysIncPath);
724 		if (!name || !(stream = fopen(name, "r")))
725 			return(FALSE);
726 		fname = name;
727 		/*
728 		 * set the MAKEFILE variable desired by System V fans -- the
729 		 * placement of the setting here means it gets set to the last
730 		 * makefile specified, as it is set by SysV make.
731 		 */
732 found:		Var_Set("MAKEFILE", fname, VAR_GLOBAL);
733 		Parse_File(fname, stream);
734 		(void)fclose(stream);
735 	}
736 	return(TRUE);
737 }
738 
739 /*-
740  * Error --
741  *	Print an error message given its format.
742  *
743  * Results:
744  *	None.
745  *
746  * Side Effects:
747  *	The message is printed.
748  */
749 /* VARARGS */
750 void
751 #if __STDC__
752 Error(char *fmt, ...)
753 #else
754 Error(va_alist)
755 	va_dcl
756 #endif
757 {
758 	va_list ap;
759 #if __STDC__
760 	va_start(ap, fmt);
761 #else
762 	char *fmt;
763 
764 	va_start(ap);
765 	fmt = va_arg(ap, char *);
766 #endif
767 	(void)vfprintf(stderr, fmt, ap);
768 	va_end(ap);
769 	(void)fprintf(stderr, "\n");
770 	(void)fflush(stderr);
771 }
772 
773 /*-
774  * Fatal --
775  *	Produce a Fatal error message. If jobs are running, waits for them
776  *	to finish.
777  *
778  * Results:
779  *	None
780  *
781  * Side Effects:
782  *	The program exits
783  */
784 /* VARARGS */
785 void
786 #if __STDC__
787 Fatal(char *fmt, ...)
788 #else
789 Fatal(va_alist)
790 	va_dcl
791 #endif
792 {
793 	va_list ap;
794 #if __STDC__
795 	va_start(ap, fmt);
796 #else
797 	char *fmt;
798 
799 	va_start(ap);
800 	fmt = va_arg(ap, char *);
801 #endif
802 	if (jobsRunning)
803 		Job_Wait();
804 
805 	(void)vfprintf(stderr, fmt, ap);
806 	va_end(ap);
807 	(void)fprintf(stderr, "\n");
808 	(void)fflush(stderr);
809 
810 	if (DEBUG(GRAPH2))
811 		Targ_PrintGraph(2);
812 	exit(2);		/* Not 1 so -q can distinguish error */
813 }
814 
815 /*
816  * Punt --
817  *	Major exception once jobs are being created. Kills all jobs, prints
818  *	a message and exits.
819  *
820  * Results:
821  *	None
822  *
823  * Side Effects:
824  *	All children are killed indiscriminately and the program Lib_Exits
825  */
826 /* VARARGS */
827 void
828 #if __STDC__
829 Punt(char *fmt, ...)
830 #else
831 Punt(va_alist)
832 	va_dcl
833 #endif
834 {
835 	va_list ap;
836 #if __STDC__
837 	va_start(ap, fmt);
838 #else
839 	char *fmt;
840 
841 	va_start(ap);
842 	fmt = va_arg(ap, char *);
843 #endif
844 
845 	(void)fprintf(stderr, "make: ");
846 	(void)vfprintf(stderr, fmt, ap);
847 	va_end(ap);
848 	(void)fprintf(stderr, "\n");
849 	(void)fflush(stderr);
850 
851 	DieHorribly();
852 }
853 
854 /*-
855  * DieHorribly --
856  *	Exit without giving a message.
857  *
858  * Results:
859  *	None
860  *
861  * Side Effects:
862  *	A big one...
863  */
864 void
865 DieHorribly()
866 {
867 	if (jobsRunning)
868 		Job_AbortAll();
869 	if (DEBUG(GRAPH2))
870 		Targ_PrintGraph(2);
871 	exit(2);		/* Not 1, so -q can distinguish error */
872 }
873 
874 /*
875  * Finish --
876  *	Called when aborting due to errors in child shell to signal
877  *	abnormal exit.
878  *
879  * Results:
880  *	None
881  *
882  * Side Effects:
883  *	The program exits
884  */
885 void
886 Finish(errors)
887 	int errors;	/* number of errors encountered in Make_Make */
888 {
889 	Fatal("%d error%s", errors, errors == 1 ? "" : "s");
890 }
891 
892 /*
893  * emalloc --
894  *	malloc, but die on error.
895  */
896 char *
897 emalloc(len)
898 	size_t len;
899 {
900 	char *p;
901 
902 	if ((p = (char *) malloc(len)) == NULL)
903 		enomem();
904 	return(p);
905 }
906 
907 /*
908  * enomem --
909  *	die when out of memory.
910  */
911 void
912 enomem()
913 {
914 	(void)fprintf(stderr, "make: %s.\n", strerror(errno));
915 	exit(2);
916 }
917 
918 /*
919  * usage --
920  *	exit with usage message
921  */
922 static void
923 usage()
924 {
925 	(void)fprintf(stderr,
926 "usage: make [-eiknqrst] [-D variable] [-d flags] [-f makefile ]\n\
927             [-I directory] [-j max_jobs] [variable=value]\n");
928 	exit(2);
929 }
930 
931 
932 int
933 PrintAddr(a, b)
934     ClientData a;
935     ClientData b;
936 {
937     printf("%lx ", (unsigned long) a);
938     return b ? 0 : 0;
939 }
940