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