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