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