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