main.c revision 144020
1/*-
2 * Copyright (c) 1988, 1989, 1990, 1993
3 *	The Regents of the University of California.  All rights reserved.
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 * @(#)main.c      8.3 (Berkeley) 3/19/94
39 */
40
41#ifndef lint
42#if 0
43static char copyright[] =
44"@(#) Copyright (c) 1988, 1989, 1990, 1993\n\
45	The Regents of the University of California.  All rights reserved.\n";
46#endif
47#endif /* not lint */
48#include <sys/cdefs.h>
49__FBSDID("$FreeBSD: head/usr.bin/make/main.c 144020 2005-03-23 12:56:15Z harti $");
50
51/*-
52 * main.c --
53 *	The main file for this entire program. Exit routines etc
54 *	reside here.
55 *
56 * Utility functions defined in this file:
57 *	Main_ParseArgLine	Takes a line of arguments, breaks them and
58 *				treats them as if they were given when first
59 *				invoked. Used by the parse module to implement
60 *				the .MFLAGS target.
61 */
62
63#ifndef MACHINE
64#include <sys/utsname.h>
65#endif
66#include <sys/param.h>
67#include <sys/stat.h>
68#include <sys/sysctl.h>
69#include <sys/time.h>
70#include <sys/queue.h>
71#include <sys/resource.h>
72#include <sys/wait.h>
73#include <err.h>
74#include <errno.h>
75#include <signal.h>
76#include <stdlib.h>
77#include <string.h>
78#include <unistd.h>
79
80#include "arch.h"
81#include "buf.h"
82#include "compat.h"
83#include "config.h"
84#include "dir.h"
85#include "globals.h"
86#include "job.h"
87#include "make.h"
88#include "nonints.h"
89#include "parse.h"
90#include "pathnames.h"
91#include "str.h"
92#include "suff.h"
93#include "targ.h"
94#include "util.h"
95#include "var.h"
96
97#define WANT_ENV_MKLVL	1
98#define	MKLVL_MAXVAL	500
99#define	MKLVL_ENVVAR	"__MKLVL__"
100
101#define	MAKEFLAGS	".MAKEFLAGS"
102
103/* Targets to be made */
104Lst create = Lst_Initializer(create);
105
106time_t			now;		/* Time at start of make */
107struct GNode		*DEFAULT;	/* .DEFAULT node */
108Boolean			allPrecious;	/* .PRECIOUS given on line by itself */
109
110static Boolean		noBuiltins;	/* -r flag */
111
112/* ordered list of makefiles to read */
113static Lst makefiles = Lst_Initializer(makefiles);
114
115static Boolean		expandVars;	/* fully expand printed variables */
116
117/* list of variables to print */
118static Lst variables = Lst_Initializer(variables);
119
120int			maxJobs;	/* -j argument */
121static Boolean          forceJobs;      /* -j argument given */
122Boolean			compatMake;	/* -B argument */
123Boolean			debug;		/* -d flag */
124Boolean			noExecute;	/* -n flag */
125Boolean			keepgoing;	/* -k flag */
126Boolean			queryFlag;	/* -q flag */
127Boolean			touchFlag;	/* -t flag */
128Boolean			usePipes;	/* !-P flag */
129Boolean			ignoreErrors;	/* -i flag */
130Boolean			beSilent;	/* -s flag */
131Boolean			beVerbose;	/* -v flag */
132Boolean			oldVars;	/* variable substitution style */
133Boolean			checkEnvFirst;	/* -e flag */
134
135/* (-E) vars to override from env */
136Lst envFirstVars = Lst_Initializer(envFirstVars);
137
138Boolean			jobsRunning;	/* TRUE if the jobs might be running */
139
140static void		MainParseArgs(int, char **);
141char			*chdir_verify_path(const char *, char *);
142static int		ReadMakefile(const char *);
143static void		usage(void);
144
145static char *curdir;			/* startup directory */
146static char *objdir;			/* where we chdir'ed to */
147
148/*
149 * Append a flag with an optional argument to MAKEFLAGS and MFLAGS
150 */
151static void
152MFLAGS_append(const char *flag, char *arg)
153{
154	char *str;
155
156	Var_Append(MAKEFLAGS, flag, VAR_GLOBAL);
157	if (arg != NULL) {
158		str = MAKEFLAGS_quote(arg);
159		Var_Append(MAKEFLAGS, str, VAR_GLOBAL);
160		free(str);
161	}
162
163	Var_Append("MFLAGS", flag, VAR_GLOBAL);
164	if (arg != NULL) {
165		str = MAKEFLAGS_quote(arg);
166		Var_Append("MFLAGS", str, VAR_GLOBAL);
167		free(str);
168	}
169}
170
171/*-
172 * MainParseArgs --
173 *	Parse a given argument vector. Called from main() and from
174 *	Main_ParseArgLine() when the .MAKEFLAGS target is used.
175 *
176 *	XXX: Deal with command line overriding .MAKEFLAGS in makefile
177 *
178 * Results:
179 *	None
180 *
181 * Side Effects:
182 *	Various global and local flags will be set depending on the flags
183 *	given
184 */
185static void
186MainParseArgs(int argc, char **argv)
187{
188	int c;
189
190	optind = 1;	/* since we're called more than once */
191#define OPTFLAGS "BC:D:E:I:PSV:Xd:ef:ij:km:nqrstv"
192rearg:	while((c = getopt(argc, argv, OPTFLAGS)) != -1) {
193		switch(c) {
194		case 'C':
195			if (chdir(optarg) == -1)
196				err(1, "chdir %s", optarg);
197			break;
198		case 'D':
199			Var_Set(optarg, "1", VAR_GLOBAL);
200			MFLAGS_append("-D", optarg);
201			break;
202		case 'I':
203			Parse_AddIncludeDir(optarg);
204			MFLAGS_append("-I", optarg);
205			break;
206		case 'V':
207			Lst_AtEnd(&variables, estrdup(optarg));
208			MFLAGS_append("-V", optarg);
209			break;
210		case 'X':
211			expandVars = FALSE;
212			break;
213		case 'B':
214			compatMake = TRUE;
215			MFLAGS_append("-B", NULL);
216			unsetenv("MAKE_JOBS_FIFO");
217			break;
218		case 'P':
219			usePipes = FALSE;
220			MFLAGS_append("-P", NULL);
221			break;
222		case 'S':
223			keepgoing = FALSE;
224			MFLAGS_append("-S", NULL);
225			break;
226		case 'd': {
227			char *modules = optarg;
228
229			for (; *modules; ++modules)
230				switch (*modules) {
231				case 'A':
232					debug = ~0;
233					break;
234				case 'a':
235					debug |= DEBUG_ARCH;
236					break;
237				case 'c':
238					debug |= DEBUG_COND;
239					break;
240				case 'd':
241					debug |= DEBUG_DIR;
242					break;
243				case 'f':
244					debug |= DEBUG_FOR;
245					break;
246				case 'g':
247					if (modules[1] == '1') {
248						debug |= DEBUG_GRAPH1;
249						++modules;
250					}
251					else if (modules[1] == '2') {
252						debug |= DEBUG_GRAPH2;
253						++modules;
254					}
255					break;
256				case 'j':
257					debug |= DEBUG_JOB;
258					break;
259				case 'l':
260					debug |= DEBUG_LOUD;
261					break;
262				case 'm':
263					debug |= DEBUG_MAKE;
264					break;
265				case 's':
266					debug |= DEBUG_SUFF;
267					break;
268				case 't':
269					debug |= DEBUG_TARG;
270					break;
271				case 'v':
272					debug |= DEBUG_VAR;
273					break;
274				default:
275					warnx("illegal argument to d option -- %c", *modules);
276					usage();
277				}
278			MFLAGS_append("-d", optarg);
279			break;
280		}
281		case 'E':
282			Lst_AtEnd(&envFirstVars, estrdup(optarg));
283			MFLAGS_append("-E", optarg);
284			break;
285		case 'e':
286			checkEnvFirst = TRUE;
287			MFLAGS_append("-e", NULL);
288			break;
289		case 'f':
290			Lst_AtEnd(&makefiles, estrdup(optarg));
291			break;
292		case 'i':
293			ignoreErrors = TRUE;
294			MFLAGS_append("-i", NULL);
295			break;
296		case 'j': {
297			char *endptr;
298
299			forceJobs = TRUE;
300			maxJobs = strtol(optarg, &endptr, 10);
301			if (maxJobs <= 0 || *endptr != '\0') {
302				warnx("illegal number, -j argument -- %s",
303				    optarg);
304				usage();
305			}
306			MFLAGS_append("-j", optarg);
307			break;
308		}
309		case 'k':
310			keepgoing = TRUE;
311			MFLAGS_append("-k", NULL);
312			break;
313		case 'm':
314			Path_AddDir(&sysIncPath, optarg);
315			MFLAGS_append("-m", optarg);
316			break;
317		case 'n':
318			noExecute = TRUE;
319			MFLAGS_append("-n", NULL);
320			break;
321		case 'q':
322			queryFlag = TRUE;
323			/* Kind of nonsensical, wot? */
324			MFLAGS_append("-q", NULL);
325			break;
326		case 'r':
327			noBuiltins = TRUE;
328			MFLAGS_append("-r", NULL);
329			break;
330		case 's':
331			beSilent = TRUE;
332			MFLAGS_append("-s", NULL);
333			break;
334		case 't':
335			touchFlag = TRUE;
336			MFLAGS_append("-t", NULL);
337			break;
338		case 'v':
339			beVerbose = TRUE;
340			MFLAGS_append("-v", NULL);
341			break;
342		default:
343		case '?':
344			usage();
345		}
346	}
347
348	oldVars = TRUE;
349
350	/*
351	 * See if the rest of the arguments are variable assignments and
352	 * perform them if so. Else take them to be targets and stuff them
353	 * on the end of the "create" list.
354	 */
355	for (argv += optind, argc -= optind; *argv; ++argv, --argc)
356		if (Parse_IsVar(*argv)) {
357			char *ptr = MAKEFLAGS_quote(*argv);
358
359			Var_Append(MAKEFLAGS, ptr, VAR_GLOBAL);
360			free(ptr);
361
362			Parse_DoVar(*argv, VAR_CMD);
363		} else {
364			if (!**argv)
365				Punt("illegal (null) argument.");
366			if (**argv == '-') {
367				if ((*argv)[1])
368					optind = 0;     /* -flag... */
369				else
370					optind = 1;     /* - */
371				goto rearg;
372			}
373			Lst_AtEnd(&create, estrdup(*argv));
374		}
375}
376
377/*-
378 * Main_ParseArgLine --
379 *  	Used by the parse module when a .MFLAGS or .MAKEFLAGS target
380 *	is encountered and by main() when reading the .MAKEFLAGS envariable.
381 *	Takes a line of arguments and breaks it into its
382 * 	component words and passes those words and the number of them to the
383 *	MainParseArgs function.
384 *	The line should have all its leading whitespace removed.
385 *
386 * Results:
387 *	None
388 *
389 * Side Effects:
390 *	Only those that come from the various arguments.
391 */
392void
393Main_ParseArgLine(char *line, int mflags)
394{
395	char **argv;			/* Manufactured argument vector */
396	int argc;			/* Number of arguments in argv */
397
398	if (line == NULL)
399		return;
400	for (; *line == ' '; ++line)
401		continue;
402	if (!*line)
403		return;
404
405	if (mflags)
406		argv = MAKEFLAGS_break(line, &argc);
407	else
408		argv = brk_string(line, &argc, TRUE);
409
410	MainParseArgs(argc, argv);
411}
412
413char *
414chdir_verify_path(const char *path, char *obpath)
415{
416	struct stat sb;
417
418	if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
419		if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) {
420			warn("warning: %s", path);
421			return (NULL);
422		}
423		return (obpath);
424	}
425
426	return (NULL);
427}
428
429static void
430catch_child(int sig __unused)
431{
432}
433
434/*
435 * In lieu of a good way to prevent every possible looping in
436 * make(1), stop there from being more than MKLVL_MAXVAL processes forked
437 * by make(1), to prevent a forkbomb from happening, in a dumb and
438 * mechanical way.
439 */
440static void
441check_make_level(void)
442{
443#ifdef WANT_ENV_MKLVL
444	char	*value = getenv(MKLVL_ENVVAR);
445	int	level = (value == NULL) ? 0 : atoi(value);
446
447	if (level < 0) {
448		errc(2, EAGAIN, "Invalid value for recursion level (%d).", level);
449	} else if (level > MKLVL_MAXVAL) {
450		errc(2, EAGAIN, "Max recursion level (%d) exceeded.", MKLVL_MAXVAL);
451	} else {
452		char new_value[32];
453		sprintf(new_value, "%d", level + 1);
454		setenv(MKLVL_ENVVAR, new_value, 1);
455	}
456#endif /* WANT_ENV_MKLVL */
457}
458
459/*-
460 * main --
461 *	The main function, for obvious reasons. Initializes variables
462 *	and a few modules, then parses the arguments give it in the
463 *	environment and on the command line. Reads the system makefile
464 *	followed by either Makefile, makefile or the file given by the
465 *	-f argument. Sets the .MAKEFLAGS PMake variable based on all the
466 *	flags it has received by then uses either the Make or the Compat
467 *	module to create the initial list of targets.
468 *
469 * Results:
470 *	If -q was given, exits -1 if anything was out-of-date. Else it exits
471 *	0.
472 *
473 * Side Effects:
474 *	The program exits when done. Targets are created. etc. etc. etc.
475 */
476int
477main(int argc, char **argv)
478{
479	Boolean outOfDate = TRUE; 	/* FALSE if all targets up to date */
480	char *p, *p1, *pathp;
481	char *path;
482	char mdpath[MAXPATHLEN];
483	char obpath[MAXPATHLEN];
484	char cdpath[MAXPATHLEN];
485    	const char *machine = getenv("MACHINE");
486	const char *machine_arch = getenv("MACHINE_ARCH");
487	const char *machine_cpu = getenv("MACHINE_CPU");
488	char *cp = NULL, *start;
489
490					/* avoid faults on read-only strings */
491	static char syspath[] = PATH_DEFSYSPATH;
492
493	{
494	/*
495	 * Catch SIGCHLD so that we get kicked out of select() when we
496	 * need to look at a child.  This is only known to matter for the
497	 * -j case (perhaps without -P).
498	 *
499	 * XXX this is intentionally misplaced.
500	 */
501	struct sigaction sa;
502
503	sigemptyset(&sa.sa_mask);
504	sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
505	sa.sa_handler = catch_child;
506	sigaction(SIGCHLD, &sa, NULL);
507	}
508
509	check_make_level();
510
511#if DEFSHELL == 2
512	/*
513	 * Turn off ENV to make ksh happier.
514	 */
515	unsetenv("ENV");
516#endif
517
518#ifdef RLIMIT_NOFILE
519	/*
520	 * get rid of resource limit on file descriptors
521	 */
522	{
523		struct rlimit rl;
524		if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
525		    rl.rlim_cur != rl.rlim_max) {
526			rl.rlim_cur = rl.rlim_max;
527			setrlimit(RLIMIT_NOFILE, &rl);
528		}
529	}
530#endif
531
532	/*
533	 * PC-98 kernel sets the `i386' string to the utsname.machine and
534	 * it cannot be distinguished from IBM-PC by uname(3).  Therefore,
535	 * we check machine.ispc98 and adjust the machine variable before
536	 * using usname(3) below.
537	 * NOTE: machdep.ispc98 was defined on 1998/8/31. At that time,
538	 * __FreeBSD_version was defined as 300003. So, this check can
539	 * safely be done with any kernel with version > 300003.
540	 */
541	if (!machine) {
542		int	ispc98;
543		size_t	len;
544
545		len = sizeof(ispc98);
546		if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
547			if (ispc98)
548				machine = "pc98";
549		}
550	}
551
552	/*
553	 * Get the name of this type of MACHINE from utsname
554	 * so we can share an executable for similar machines.
555	 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
556	 *
557	 * Note that while MACHINE is decided at run-time,
558	 * MACHINE_ARCH is always known at compile time.
559	 */
560	if (!machine) {
561#ifndef MACHINE
562	    static struct utsname utsname;
563
564	    if (uname(&utsname) == -1)
565		    err(2, "uname");
566	    machine = utsname.machine;
567#else
568	    machine = MACHINE;
569#endif
570	}
571
572	if (!machine_arch) {
573#ifndef MACHINE_ARCH
574		machine_arch = "unknown";
575#else
576		machine_arch = MACHINE_ARCH;
577#endif
578	}
579
580	/*
581	 * Set machine_cpu to the minumum supported CPU revision based
582	 * on the target architecture, if not already set.
583	 */
584	if (!machine_cpu) {
585		if (!strcmp(machine_arch, "i386"))
586			machine_cpu = "i386";
587		else if (!strcmp(machine_arch, "alpha"))
588			machine_cpu = "ev4";
589		else
590			machine_cpu = "unknown";
591	}
592
593	expandVars = TRUE;
594	beSilent = FALSE;		/* Print commands as executed */
595	ignoreErrors = FALSE;		/* Pay attention to non-zero returns */
596	noExecute = FALSE;		/* Execute all commands */
597	keepgoing = FALSE;		/* Stop on error */
598	allPrecious = FALSE;		/* Remove targets when interrupted */
599	queryFlag = FALSE;		/* This is not just a check-run */
600	noBuiltins = FALSE;		/* Read the built-in rules */
601	touchFlag = FALSE;		/* Actually update targets */
602	usePipes = TRUE;		/* Catch child output in pipes */
603	debug = 0;			/* No debug verbosity, please. */
604	jobsRunning = FALSE;
605
606	maxJobs = DEFMAXJOBS;
607	forceJobs = FALSE;              /* No -j flag */
608	compatMake = FALSE;		/* No compat mode */
609
610	/*
611	 * Initialize the parsing, directory and variable modules to prepare
612	 * for the reading of inclusion paths and variable settings on the
613	 * command line
614	 */
615	Dir_Init();		/* Initialize directory structures so -I flags
616				 * can be processed correctly */
617	Parse_Init();		/* Need to initialize the paths of #include
618				 * directories */
619	Var_Init();		/* As well as the lists of variables for
620				 * parsing arguments */
621        str_init();
622
623	/*
624	 * Initialize various variables.
625	 *	MAKE also gets this name, for compatibility
626	 *	.MAKEFLAGS gets set to the empty string just in case.
627	 *	MFLAGS also gets initialized empty, for compatibility.
628	 */
629	Var_Set("MAKE", argv[0], VAR_GLOBAL);
630	Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
631	Var_Set("MFLAGS", "", VAR_GLOBAL);
632	Var_Set("MACHINE", machine, VAR_GLOBAL);
633	Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
634	Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
635#ifdef MAKE_VERSION
636	Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
637#endif
638
639	/*
640	 * First snag any flags out of the MAKE environment variable.
641	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
642	 * in a different format).
643	 */
644	Main_ParseArgLine(getenv("MAKEFLAGS"), 1);
645
646	MainParseArgs(argc, argv);
647
648	/*
649	 * Find where we are...
650	 * All this code is so that we know where we are when we start up
651	 * on a different machine with pmake.
652	 */
653	curdir = cdpath;
654	if (getcwd(curdir, MAXPATHLEN) == NULL)
655		err(2, NULL);
656
657	{
658	struct stat sa;
659
660	if (stat(curdir, &sa) == -1)
661	    err(2, "%s", curdir);
662	}
663
664	/*
665	 * The object directory location is determined using the
666	 * following order of preference:
667	 *
668	 *	1. MAKEOBJDIRPREFIX`cwd`
669	 *	2. MAKEOBJDIR
670	 *	3. PATH_OBJDIR.${MACHINE}
671	 *	4. PATH_OBJDIR
672	 *	5. PATH_OBJDIRPREFIX`cwd`
673	 *
674	 * If one of the first two fails, use the current directory.
675	 * If the remaining three all fail, use the current directory.
676	 *
677	 * Once things are initted,
678	 * have to add the original directory to the search path,
679	 * and modify the paths for the Makefiles apropriately.  The
680	 * current directory is also placed as a variable for make scripts.
681	 */
682	if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
683		if (!(path = getenv("MAKEOBJDIR"))) {
684			path = PATH_OBJDIR;
685			pathp = PATH_OBJDIRPREFIX;
686			snprintf(mdpath, MAXPATHLEN, "%s.%s",
687					path, machine);
688			if (!(objdir = chdir_verify_path(mdpath, obpath)))
689				if (!(objdir=chdir_verify_path(path, obpath))) {
690					snprintf(mdpath, MAXPATHLEN,
691							"%s%s", pathp, curdir);
692					if (!(objdir=chdir_verify_path(mdpath,
693								       obpath)))
694						objdir = curdir;
695				}
696		}
697		else if (!(objdir = chdir_verify_path(path, obpath)))
698			objdir = curdir;
699	}
700	else {
701		snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
702		if (!(objdir = chdir_verify_path(mdpath, obpath)))
703			objdir = curdir;
704	}
705	Dir_InitDot();		/* Initialize the "." directory */
706	if (objdir != curdir)
707		Path_AddDir(&dirSearchPath, curdir);
708	Var_Set(".CURDIR", curdir, VAR_GLOBAL);
709	Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
710
711	if (getenv("MAKE_JOBS_FIFO") != NULL)
712		forceJobs = TRUE;
713	/*
714	 * Be compatible if user did not specify -j and did not explicitly
715	 * turned compatibility on
716	 */
717	if (!compatMake && !forceJobs)
718		compatMake = TRUE;
719
720	/*
721	 * Initialize archive, target and suffix modules in preparation for
722	 * parsing the makefile(s)
723	 */
724	Arch_Init();
725	Targ_Init();
726	Suff_Init();
727
728	DEFAULT = NULL;
729	time(&now);
730
731	/*
732	 * Set up the .TARGETS variable to contain the list of targets to be
733	 * created. If none specified, make the variable empty -- the parser
734	 * will fill the thing in with the default or .MAIN target.
735	 */
736	if (!Lst_IsEmpty(&create)) {
737		LstNode *ln;
738
739		for (ln = Lst_First(&create); ln != NULL; ln = Lst_Succ(ln)) {
740			char *name = Lst_Datum(ln);
741
742			Var_Append(".TARGETS", name, VAR_GLOBAL);
743		}
744	} else
745		Var_Set(".TARGETS", "", VAR_GLOBAL);
746
747
748	/*
749	 * If no user-supplied system path was given (through the -m option)
750	 * add the directories from the DEFSYSPATH (more than one may be given
751	 * as dir1:...:dirn) to the system include path.
752	 */
753	if (TAILQ_EMPTY(&sysIncPath)) {
754		for (start = syspath; *start != '\0'; start = cp) {
755			for (cp = start; *cp != '\0' && *cp != ':'; cp++)
756				continue;
757			if (*cp == '\0') {
758				Path_AddDir(&sysIncPath, start);
759			} else {
760				*cp++ = '\0';
761				Path_AddDir(&sysIncPath, start);
762			}
763		}
764	}
765
766	/*
767	 * Read in the built-in rules first, followed by the specified
768	 * makefile, if it was (makefile != (char *) NULL), or the default
769	 * Makefile and makefile, in that order, if it wasn't.
770	 */
771	if (!noBuiltins) {
772		/* Path of sys.mk */
773		Lst sysMkPath = Lst_Initializer(sysMkPath);
774		LstNode *ln;
775
776		Path_Expand(PATH_DEFSYSMK, &sysIncPath, &sysMkPath);
777		if (Lst_IsEmpty(&sysMkPath))
778			Fatal("make: no system rules (%s).", PATH_DEFSYSMK);
779		LST_FOREACH(ln, &sysMkPath) {
780			if (!ReadMakefile(Lst_Datum(ln)))
781				break;
782		}
783		if (ln != NULL)
784			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
785		Lst_Destroy(&sysMkPath, free);
786	}
787
788	if (!Lst_IsEmpty(&makefiles)) {
789		LstNode *ln;
790
791		LST_FOREACH(ln, &makefiles) {
792			if (!ReadMakefile(Lst_Datum(ln)))
793				break;
794		}
795		if (ln != NULL)
796			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
797	} else if (!ReadMakefile("BSDmakefile"))
798	    if (!ReadMakefile("makefile"))
799		ReadMakefile("Makefile");
800
801	ReadMakefile(".depend");
802
803	/* Install all the flags into the MAKE envariable. */
804	if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
805		setenv("MAKEFLAGS", p, 1);
806	free(p1);
807
808	/*
809	 * For compatibility, look at the directories in the VPATH variable
810	 * and add them to the search path, if the variable is defined. The
811	 * variable's value is in the same format as the PATH envariable, i.e.
812	 * <directory>:<directory>:<directory>...
813	 */
814	if (Var_Exists("VPATH", VAR_CMD)) {
815		/*
816		 * GCC stores string constants in read-only memory, but
817		 * Var_Subst will want to write this thing, so store it
818		 * in an array
819		 */
820		static char VPATH[] = "${VPATH}";
821		Buffer	*buf;
822		char	*vpath;
823		char	*ptr;
824		char	savec;
825
826		buf = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
827
828		vpath = Buf_Data(buf);
829		do {
830			/* skip to end of directory */
831			for (ptr = vpath; *ptr != ':' && *ptr != '\0'; ptr++)
832				;
833
834			/* Save terminator character so know when to stop */
835			savec = *ptr;
836			*ptr = '\0';
837
838			/* Add directory to search path */
839			Path_AddDir(&dirSearchPath, vpath);
840
841			vpath = ptr + 1;
842		} while (savec != '\0');
843
844		Buf_Destroy(buf, TRUE);
845	}
846
847	/*
848	 * Now that all search paths have been read for suffixes et al, it's
849	 * time to add the default search path to their lists...
850	 */
851	Suff_DoPaths();
852
853	/* print the initial graph, if the user requested it */
854	if (DEBUG(GRAPH1))
855		Targ_PrintGraph(1);
856
857	/* print the values of any variables requested by the user */
858	if (Lst_IsEmpty(&variables)) {
859		/*
860		 * Since the user has not requested that any variables
861		 * be printed, we can build targets.
862		 *
863		 * Have read the entire graph and need to make a list of targets
864		 * to create. If none was given on the command line, we consult
865		 * the parsing module to find the main target(s) to create.
866		 */
867		Lst targs = Lst_Initializer(targs);
868
869		if (Lst_IsEmpty(&create))
870			Parse_MainName(&targs);
871		else
872			Targ_FindList(&targs, &create, TARG_CREATE);
873
874		if (compatMake) {
875			/*
876			 * Compat_Init will take care of creating
877			 * all the targets as well as initializing
878			 * the module.
879			 */
880			Compat_Run(&targs);
881			outOfDate = 0;
882		} else {
883			/*
884			 * Initialize job module before traversing
885			 * the graph, now that any .BEGIN and .END
886			 * targets have been read.  This is done
887			 * only if the -q flag wasn't given (to
888			 * prevent the .BEGIN from being executed
889			 * should it exist).
890			 */
891			if (!queryFlag) {
892				Job_Init(maxJobs);
893				jobsRunning = TRUE;
894			}
895
896			/* Traverse the graph, checking on all the targets */
897			outOfDate = Make_Run(&targs);
898		}
899		Lst_Destroy(&targs, NOFREE);
900
901	} else {
902		/*
903		 * Print the values of any variables requested by
904		 * the user.
905		 */
906		LstNode		*n;
907		const char	*name;
908		char		*v;
909		char		*value;
910
911		LST_FOREACH(n, &variables) {
912			name = Lst_Datum(n);
913			if (expandVars) {
914				v = emalloc(strlen(name) + 1 + 3);
915				sprintf(v, "${%s}", name);
916
917				value = Buf_Peel(Var_Subst(NULL, v,
918				    VAR_GLOBAL, FALSE));
919				printf("%s\n", value);
920
921				free(v);
922				free(value);
923			} else {
924				value = Var_Value(name, VAR_GLOBAL, &v);
925				printf("%s\n", value != NULL ? value : "");
926				if (v != NULL)
927					free(v);
928			}
929		}
930	}
931
932	Lst_Destroy(&variables, free);
933	Lst_Destroy(&makefiles, free);
934	Lst_Destroy(&create, free);
935
936	/* print the graph now it's been processed if the user requested it */
937	if (DEBUG(GRAPH2))
938		Targ_PrintGraph(2);
939
940	if (queryFlag && outOfDate)
941		return (1);
942	else
943		return (0);
944}
945
946/*-
947 * ReadMakefile  --
948 *	Open and parse the given makefile.
949 *
950 * Results:
951 *	TRUE if ok. FALSE if couldn't open file.
952 *
953 * Side Effects:
954 *	lots
955 */
956static Boolean
957ReadMakefile(const char *p)
958{
959	char *fname;			/* makefile to read */
960	FILE *stream;
961	char *name, path[MAXPATHLEN];
962	char *MAKEFILE;
963	int setMAKEFILE;
964
965	/* XXX - remove this once constification is done */
966	fname = estrdup(p);
967
968	if (!strcmp(fname, "-")) {
969		Parse_File("(stdin)", stdin);
970		Var_Set("MAKEFILE", "", VAR_GLOBAL);
971	} else {
972		setMAKEFILE = strcmp(fname, ".depend");
973
974		/* if we've chdir'd, rebuild the path name */
975		if (curdir != objdir && *fname != '/') {
976			snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
977			/*
978			 * XXX The realpath stuff breaks relative includes
979			 * XXX in some cases.   The problem likely is in
980			 * XXX parse.c where it does special things in
981			 * XXX ParseDoInclude if the file is relateive
982			 * XXX or absolute and not a system file.  There
983			 * XXX it assumes that if the current file that's
984			 * XXX being included is absolute, that any files
985			 * XXX that it includes shouldn't do the -I path
986			 * XXX stuff, which is inconsistant with historical
987			 * XXX behavior.  However, I can't pentrate the mists
988			 * XXX further, so I'm putting this workaround in
989			 * XXX here until such time as the underlying bug
990			 * XXX can be fixed.
991			 */
992#if THIS_BREAKS_THINGS
993			if (realpath(path, path) != NULL &&
994			    (stream = fopen(path, "r")) != NULL) {
995				MAKEFILE = fname;
996				fname = path;
997				goto found;
998			}
999		} else if (realpath(fname, path) != NULL) {
1000			MAKEFILE = fname;
1001			fname = path;
1002			if ((stream = fopen(fname, "r")) != NULL)
1003				goto found;
1004		}
1005#else
1006			if ((stream = fopen(path, "r")) != NULL) {
1007				MAKEFILE = fname;
1008				fname = path;
1009				goto found;
1010			}
1011		} else {
1012			MAKEFILE = fname;
1013			if ((stream = fopen(fname, "r")) != NULL)
1014				goto found;
1015		}
1016#endif
1017		/* look in -I and system include directories. */
1018		name = Path_FindFile(fname, &parseIncPath);
1019		if (!name)
1020			name = Path_FindFile(fname, &sysIncPath);
1021		if (!name || !(stream = fopen(name, "r")))
1022			return (FALSE);
1023		MAKEFILE = fname = name;
1024		/*
1025		 * set the MAKEFILE variable desired by System V fans -- the
1026		 * placement of the setting here means it gets set to the last
1027		 * makefile specified, as it is set by SysV make.
1028		 */
1029found:
1030		if (setMAKEFILE)
1031			Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
1032		Parse_File(fname, stream);
1033		fclose(stream);
1034	}
1035	return (TRUE);
1036}
1037
1038/*-
1039 * Cmd_Exec --
1040 *	Execute the command in cmd, and return the output of that command
1041 *	in a string.
1042 *
1043 * Results:
1044 *	A string containing the output of the command, or the empty string
1045 *	If error is not NULL, it contains the reason for the command failure
1046 *
1047 * Side Effects:
1048 *	The string must be freed by the caller.
1049 */
1050Buffer *
1051Cmd_Exec(char *cmd, const char **error)
1052{
1053    int 	fds[2];	    	/* Pipe streams */
1054    int 	cpid;	    	/* Child PID */
1055    int 	pid;	    	/* PID from wait() */
1056    int		status;		/* command exit status */
1057    Buffer	*buf;		/* buffer to store the result */
1058    ssize_t	rcnt;
1059
1060    *error = NULL;
1061    buf = Buf_Init(0);
1062
1063    if (shellPath == NULL)
1064	Shell_Init();
1065    /*
1066     * Open a pipe for fetching its output
1067     */
1068    if (pipe(fds) == -1) {
1069	*error = "Couldn't create pipe for \"%s\"";
1070	return (buf);
1071    }
1072
1073    /*
1074     * Fork
1075     */
1076    switch (cpid = vfork()) {
1077    case 0:
1078	/*
1079	 * Close input side of pipe
1080	 */
1081	close(fds[0]);
1082
1083	/*
1084	 * Duplicate the output stream to the shell's output, then
1085	 * shut the extra thing down. Note we don't fetch the error
1086	 * stream...why not? Why?
1087	 */
1088	dup2(fds[1], 1);
1089	close(fds[1]);
1090
1091	{
1092	    char	*args[4];
1093
1094	    /* Set up arguments for shell */
1095	    args[0] = shellName;
1096	    args[1] = "-c";
1097	    args[2] = cmd;
1098	    args[3] = NULL;
1099
1100	    execv(shellPath, args);
1101	    _exit(1);
1102	    /*NOTREACHED*/
1103	}
1104
1105    case -1:
1106	*error = "Couldn't exec \"%s\"";
1107	return (buf);
1108
1109    default:
1110	/*
1111	 * No need for the writing half
1112	 */
1113	close(fds[1]);
1114
1115	do {
1116	    char   result[BUFSIZ];
1117	    rcnt = read(fds[0], result, sizeof(result));
1118	    if (rcnt != -1)
1119		Buf_AddBytes(buf, (size_t)rcnt, (Byte *)result);
1120	} while (rcnt > 0 || (rcnt == -1 && errno == EINTR));
1121
1122	if (rcnt == -1)
1123	    *error = "Error reading shell's output for \"%s\"";
1124
1125	/*
1126	 * Close the input side of the pipe.
1127	 */
1128	close(fds[0]);
1129
1130	/*
1131	 * Wait for the process to exit.
1132	 */
1133	while (((pid = wait(&status)) != cpid) && (pid >= 0))
1134	    continue;
1135
1136	if (status)
1137	    *error = "\"%s\" returned non-zero status";
1138
1139	Buf_StripNewlines(buf);
1140
1141	break;
1142    }
1143    return (buf);
1144}
1145
1146/*
1147 * usage --
1148 *	exit with usage message
1149 */
1150static void
1151usage(void)
1152{
1153	fprintf(stderr, "%s\n%s\n%s\n",
1154"usage: make [-BPSXeiknqrstv] [-C directory] [-D variable] [-d flags]",
1155"            [-E variable] [-f makefile] [-I directory] [-j max_jobs]",
1156"            [-m directory] [-V variable] [variable=value] [target ...]");
1157	exit(2);
1158}
1159