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