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