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