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