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