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