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