main.c revision 213493
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 213493 2010-10-06 20:49:45Z imp $");
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#include <sys/param.h>
65#include <sys/stat.h>
66#include <sys/sysctl.h>
67#include <sys/time.h>
68#include <sys/queue.h>
69#include <sys/resource.h>
70#include <sys/utsname.h>
71#include <sys/wait.h>
72#include <err.h>
73#include <errno.h>
74#include <stdlib.h>
75#include <string.h>
76#include <unistd.h>
77
78#include "arch.h"
79#include "buf.h"
80#include "config.h"
81#include "dir.h"
82#include "globals.h"
83#include "GNode.h"
84#include "job.h"
85#include "make.h"
86#include "parse.h"
87#include "pathnames.h"
88#include "shell.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/* ordered list of source makefiles */
105static Lst source_makefiles = Lst_Initializer(source_makefiles);
106
107/* list of variables to print */
108static Lst variables = Lst_Initializer(variables);
109
110static Boolean	expandVars;	/* fully expand printed variables */
111static Boolean	noBuiltins;	/* -r flag */
112static Boolean	forceJobs;	/* -j argument given */
113static char	*curdir;	/* startup directory */
114static char	*objdir;	/* where we chdir'ed to */
115static char	**save_argv;	/* saved argv */
116static char	*save_makeflags;/* saved MAKEFLAGS */
117
118/* (-E) vars to override from env */
119Lst envFirstVars = Lst_Initializer(envFirstVars);
120
121/* Targets to be made */
122Lst create = Lst_Initializer(create);
123
124Boolean		allPrecious;	/* .PRECIOUS given on line by itself */
125Boolean		is_posix;	/* .POSIX target seen */
126Boolean		mfAutoDeps;	/* .MAKEFILEDEPS target seen */
127Boolean		remakingMakefiles; /* True if remaking makefiles is in progress */
128Boolean		beSilent;	/* -s flag */
129Boolean		beVerbose;	/* -v flag */
130Boolean		beQuiet;	/* -Q flag */
131Boolean		compatMake;	/* -B argument */
132int		debug;		/* -d flag */
133Boolean		ignoreErrors;	/* -i flag */
134int		jobLimit;	/* -j argument */
135int		makeErrors;	/* Number of targets not remade due to errors */
136Boolean		jobsRunning;	/* TRUE if the jobs might be running */
137Boolean		keepgoing;	/* -k flag */
138Boolean		noExecute;	/* -n flag */
139Boolean		printGraphOnly;	/* -p flag */
140Boolean		queryFlag;	/* -q flag */
141Boolean		touchFlag;	/* -t flag */
142Boolean		usePipes;	/* !-P flag */
143uint32_t	warn_cmd;	/* command line warning flags */
144uint32_t	warn_flags;	/* actual warning flags */
145uint32_t	warn_nocmd;	/* command line no-warning flags */
146
147time_t		now;		/* Time at start of make */
148struct GNode	*DEFAULT;	/* .DEFAULT node */
149
150/**
151 * Exit with usage message.
152 */
153static void
154usage(void)
155{
156	fprintf(stderr,
157	    "usage: make [-BPSXeiknpqrstv] [-C directory] [-D variable]\n"
158	    "\t[-d flags] [-E variable] [-f makefile] [-I directory]\n"
159	    "\t[-j max_jobs] [-m directory] [-V variable]\n"
160	    "\t[variable=value] [target ...]\n");
161	exit(2);
162}
163
164/**
165 * MFLAGS_append
166 *	Append a flag with an optional argument to MAKEFLAGS and MFLAGS
167 */
168static void
169MFLAGS_append(const char *flag, char *arg)
170{
171	char *str;
172
173	Var_Append(".MAKEFLAGS", flag, VAR_GLOBAL);
174	if (arg != NULL) {
175		str = MAKEFLAGS_quote(arg);
176		Var_Append(".MAKEFLAGS", str, VAR_GLOBAL);
177		free(str);
178	}
179
180	Var_Append("MFLAGS", flag, VAR_GLOBAL);
181	if (arg != NULL) {
182		str = MAKEFLAGS_quote(arg);
183		Var_Append("MFLAGS", str, VAR_GLOBAL);
184		free(str);
185	}
186}
187
188/**
189 * Main_ParseWarn
190 *
191 *	Handle argument to warning option.
192 */
193int
194Main_ParseWarn(const char *arg, int iscmd)
195{
196	int i, neg;
197
198	static const struct {
199		const char	*option;
200		uint32_t	flag;
201	} options[] = {
202		{ "dirsyntax",	WARN_DIRSYNTAX },
203		{ NULL,		0 }
204	};
205
206	neg = 0;
207	if (arg[0] == 'n' && arg[1] == 'o') {
208		neg = 1;
209		arg += 2;
210	}
211
212	for (i = 0; options[i].option != NULL; i++)
213		if (strcmp(arg, options[i].option) == 0)
214			break;
215
216	if (options[i].option == NULL)
217		/* unknown option */
218		return (-1);
219
220	if (iscmd) {
221		if (!neg) {
222			warn_cmd |= options[i].flag;
223			warn_nocmd &= ~options[i].flag;
224			warn_flags |= options[i].flag;
225		} else {
226			warn_nocmd |= options[i].flag;
227			warn_cmd &= ~options[i].flag;
228			warn_flags &= ~options[i].flag;
229		}
230	} else {
231		if (!neg) {
232			warn_flags |= (options[i].flag & ~warn_nocmd);
233		} else {
234			warn_flags &= ~(options[i].flag | warn_cmd);
235		}
236	}
237	return (0);
238}
239
240/**
241 * Open and parse the given makefile.
242 *
243 * Results:
244 *	TRUE if ok. FALSE if couldn't open file.
245 */
246static Boolean
247ReadMakefile(const char p[])
248{
249	char *fname, *fnamesave;	/* makefile to read */
250	FILE *stream;
251	char *name, path[MAXPATHLEN];
252	char *MAKEFILE;
253	int setMAKEFILE;
254
255	/* XXX - remove this once constification is done */
256	fnamesave = fname = estrdup(p);
257
258	if (!strcmp(fname, "-")) {
259		Parse_File("(stdin)", stdin);
260		Var_SetGlobal("MAKEFILE", "");
261	} else {
262		setMAKEFILE = strcmp(fname, ".depend");
263
264		/* if we've chdir'd, rebuild the path name */
265		if (curdir != objdir && *fname != '/') {
266			snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
267			/*
268			 * XXX The realpath stuff breaks relative includes
269			 * XXX in some cases.   The problem likely is in
270			 * XXX parse.c where it does special things in
271			 * XXX ParseDoInclude if the file is relateive
272			 * XXX or absolute and not a system file.  There
273			 * XXX it assumes that if the current file that's
274			 * XXX being included is absolute, that any files
275			 * XXX that it includes shouldn't do the -I path
276			 * XXX stuff, which is inconsistant with historical
277			 * XXX behavior.  However, I can't pentrate the mists
278			 * XXX further, so I'm putting this workaround in
279			 * XXX here until such time as the underlying bug
280			 * XXX can be fixed.
281			 */
282#if THIS_BREAKS_THINGS
283			if (realpath(path, path) != NULL &&
284			    (stream = fopen(path, "r")) != NULL) {
285				MAKEFILE = fname;
286				fname = path;
287				goto found;
288			}
289		} else if (realpath(fname, path) != NULL) {
290			MAKEFILE = fname;
291			fname = path;
292			if ((stream = fopen(fname, "r")) != NULL)
293				goto found;
294		}
295#else
296			if ((stream = fopen(path, "r")) != NULL) {
297				MAKEFILE = fname;
298				fname = path;
299				goto found;
300			}
301		} else {
302			MAKEFILE = fname;
303			if ((stream = fopen(fname, "r")) != NULL)
304				goto found;
305		}
306#endif
307		/* look in -I and system include directories. */
308		name = Path_FindFile(fname, &parseIncPath);
309		if (!name)
310			name = Path_FindFile(fname, &sysIncPath);
311		if (!name || !(stream = fopen(name, "r"))) {
312			free(fnamesave);
313			return (FALSE);
314		}
315		MAKEFILE = fname = name;
316		/*
317		 * set the MAKEFILE variable desired by System V fans -- the
318		 * placement of the setting here means it gets set to the last
319		 * makefile specified, as it is set by SysV make.
320		 */
321found:
322		if (setMAKEFILE)
323			Var_SetGlobal("MAKEFILE", MAKEFILE);
324		Parse_File(fname, stream);
325	}
326	free(fnamesave);
327	return (TRUE);
328}
329
330/**
331 * Open and parse the given makefile.
332 * If open is successful add it to the list of makefiles.
333 *
334 * Results:
335 *	TRUE if ok. FALSE if couldn't open file.
336 */
337static Boolean
338TryReadMakefile(const char p[])
339{
340	char *data;
341	LstNode *last = Lst_Last(&source_makefiles);
342
343	if (!ReadMakefile(p))
344		return (FALSE);
345
346	data = estrdup(p);
347	if (last == NULL) {
348		LstNode *first = Lst_First(&source_makefiles);
349		Lst_Insert(&source_makefiles, first, data);
350	} else
351		Lst_Append(&source_makefiles, last, estrdup(p));
352	return (TRUE);
353}
354
355/**
356 * MainParseArgs
357 *	Parse a given argument vector. Called from main() and from
358 *	Main_ParseArgLine() when the .MAKEFLAGS target is used.
359 *
360 *	XXX: Deal with command line overriding .MAKEFLAGS in makefile
361 *
362 * Side Effects:
363 *	Various global and local flags will be set depending on the flags
364 *	given
365 */
366static void
367MainParseArgs(int argc, char **argv)
368{
369	int c;
370	Boolean	found_dd = FALSE;
371	char found_dir[MAXPATHLEN + 1];	/* for searching for sys.mk */
372
373rearg:
374	optind = 1;	/* since we're called more than once */
375	optreset = 1;
376#define OPTFLAGS "ABC:D:d:E:ef:I:ij:km:nPpQqrSstV:vXx:"
377	for (;;) {
378		if ((optind < argc) && strcmp(argv[optind], "--") == 0) {
379			found_dd = TRUE;
380		}
381		if ((c = getopt(argc, argv, OPTFLAGS)) == -1) {
382			break;
383		}
384		switch(c) {
385
386		case 'A':
387			arch_fatal = FALSE;
388			MFLAGS_append("-A", NULL);
389			break;
390		case 'B':
391			compatMake = TRUE;
392			MFLAGS_append("-B", NULL);
393			unsetenv("MAKE_JOBS_FIFO");
394			break;
395		case 'C':
396			if (chdir(optarg) == -1)
397				err(1, "chdir %s", optarg);
398			if (getcwd(curdir, MAXPATHLEN) == NULL)
399				err(2, NULL);
400			break;
401		case 'D':
402			Var_SetGlobal(optarg, "1");
403			MFLAGS_append("-D", optarg);
404			break;
405		case 'd': {
406			char *modules = optarg;
407
408			for (; *modules; ++modules)
409				switch (*modules) {
410				case 'A':
411					debug = ~0;
412					break;
413				case 'a':
414					debug |= DEBUG_ARCH;
415					break;
416				case 'c':
417					debug |= DEBUG_COND;
418					break;
419				case 'd':
420					debug |= DEBUG_DIR;
421					break;
422				case 'f':
423					debug |= DEBUG_FOR;
424					break;
425				case 'g':
426					if (modules[1] == '1') {
427						debug |= DEBUG_GRAPH1;
428						++modules;
429					}
430					else if (modules[1] == '2') {
431						debug |= DEBUG_GRAPH2;
432						++modules;
433					}
434					break;
435				case 'j':
436					debug |= DEBUG_JOB;
437					break;
438				case 'l':
439					debug |= DEBUG_LOUD;
440					break;
441				case 'm':
442					debug |= DEBUG_MAKE;
443					break;
444				case 's':
445					debug |= DEBUG_SUFF;
446					break;
447				case 't':
448					debug |= DEBUG_TARG;
449					break;
450				case 'v':
451					debug |= DEBUG_VAR;
452					break;
453				default:
454					warnx("illegal argument to d option "
455					    "-- %c", *modules);
456					usage();
457				}
458			MFLAGS_append("-d", optarg);
459			break;
460		}
461		case 'E':
462			Lst_AtEnd(&envFirstVars, estrdup(optarg));
463			MFLAGS_append("-E", optarg);
464			break;
465		case 'e':
466			checkEnvFirst = TRUE;
467			MFLAGS_append("-e", NULL);
468			break;
469		case 'f':
470			Lst_AtEnd(&makefiles, estrdup(optarg));
471			break;
472		case 'I':
473			Parse_AddIncludeDir(optarg);
474			MFLAGS_append("-I", optarg);
475			break;
476		case 'i':
477			ignoreErrors = TRUE;
478			MFLAGS_append("-i", NULL);
479			break;
480		case 'j': {
481			char *endptr;
482
483			forceJobs = TRUE;
484			jobLimit = strtol(optarg, &endptr, 10);
485			if (jobLimit <= 0 || *endptr != '\0') {
486				warnx("illegal number, -j argument -- %s",
487				    optarg);
488				usage();
489			}
490			MFLAGS_append("-j", optarg);
491			break;
492		}
493		case 'k':
494			keepgoing = TRUE;
495			MFLAGS_append("-k", NULL);
496			break;
497		case 'm':
498			/* look for magic parent directory search string */
499			if (strncmp(".../", optarg, 4) == 0) {
500				if (!Dir_FindHereOrAbove(curdir, optarg + 4,
501				    found_dir, sizeof(found_dir)))
502					break;		/* nothing doing */
503				Path_AddDir(&sysIncPath, found_dir);
504			} else {
505				Path_AddDir(&sysIncPath, optarg);
506			}
507			MFLAGS_append("-m", optarg);
508			break;
509		case 'n':
510			noExecute = TRUE;
511			MFLAGS_append("-n", NULL);
512			break;
513		case 'P':
514			usePipes = FALSE;
515			MFLAGS_append("-P", NULL);
516			break;
517		case 'p':
518			printGraphOnly = TRUE;
519			debug |= DEBUG_GRAPH1;
520			break;
521		case 'Q':
522			beQuiet = TRUE;
523			beVerbose = FALSE;
524			MFLAGS_append("-Q", NULL);
525			break;
526		case 'q':
527			queryFlag = TRUE;
528			/* Kind of nonsensical, wot? */
529			MFLAGS_append("-q", NULL);
530			break;
531		case 'r':
532			noBuiltins = TRUE;
533			MFLAGS_append("-r", NULL);
534			break;
535		case 'S':
536			keepgoing = FALSE;
537			MFLAGS_append("-S", NULL);
538			break;
539		case 's':
540			beSilent = TRUE;
541			MFLAGS_append("-s", NULL);
542			break;
543		case 't':
544			touchFlag = TRUE;
545			MFLAGS_append("-t", NULL);
546			break;
547		case 'V':
548			Lst_AtEnd(&variables, estrdup(optarg));
549			MFLAGS_append("-V", optarg);
550			break;
551		case 'v':
552			beVerbose = TRUE;
553			beQuiet = FALSE;
554			MFLAGS_append("-v", NULL);
555			break;
556		case 'X':
557			expandVars = FALSE;
558			break;
559		case 'x':
560			if (Main_ParseWarn(optarg, 1) != -1)
561				MFLAGS_append("-x", optarg);
562			break;
563
564		default:
565		case '?':
566			usage();
567		}
568	}
569	argv += optind;
570	argc -= optind;
571
572	oldVars = TRUE;
573
574	/*
575	 * Parse the rest of the arguments.
576	 *	o Check for variable assignments and perform them if so.
577	 *	o Check for more flags and restart getopt if so.
578	 *	o Anything else is taken to be a target and added
579	 *	  to the end of the "create" list.
580	 */
581	for (; *argv != NULL; ++argv, --argc) {
582		if (Parse_IsVar(*argv)) {
583			char *ptr = MAKEFLAGS_quote(*argv);
584			char *v = estrdup(*argv);
585
586			Var_Append(".MAKEFLAGS", ptr, VAR_GLOBAL);
587			Parse_DoVar(v, VAR_CMD);
588			free(ptr);
589			free(v);
590
591		} else if ((*argv)[0] == '-') {
592			if ((*argv)[1] == '\0') {
593				/*
594				 * (*argv) is a single dash, so we
595				 * just ignore it.
596				 */
597			} else if (found_dd) {
598				/*
599				 * Double dash has been found, ignore
600				 * any more options.  But what do we do
601				 * with it?  For now treat it like a target.
602				 */
603				Lst_AtEnd(&create, estrdup(*argv));
604			} else {
605				/*
606				 * (*argv) is a -flag, so backup argv and
607				 * argc.  getopt() expects options to start
608				 * in the 2nd position.
609				 */
610				argc++;
611				argv--;
612				goto rearg;
613			}
614
615		} else if ((*argv)[0] == '\0') {
616			Punt("illegal (null) argument.");
617
618		} else {
619			Lst_AtEnd(&create, estrdup(*argv));
620		}
621	}
622}
623
624/**
625 * Main_ParseArgLine
626 *	Used by the parse module when a .MFLAGS or .MAKEFLAGS target
627 *	is encountered and by main() when reading the .MAKEFLAGS envariable.
628 *	Takes a line of arguments and breaks it into its
629 *	component words and passes those words and the number of them to the
630 *	MainParseArgs function.
631 *	The line should have all its leading whitespace removed.
632 *
633 * Side Effects:
634 *	Only those that come from the various arguments.
635 */
636void
637Main_ParseArgLine(char *line, int mflags)
638{
639	ArgArray	aa;
640
641	if (line == NULL)
642		return;
643	for (; *line == ' '; ++line)
644		continue;
645	if (!*line)
646		return;
647
648	if (mflags)
649		MAKEFLAGS_break(&aa, line);
650	else
651		brk_string(&aa, line, TRUE);
652
653	MainParseArgs(aa.argc, aa.argv);
654	ArgArray_Done(&aa);
655}
656
657static char *
658chdir_verify_path(const char *path, char *obpath)
659{
660	struct stat sb;
661
662	if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
663		if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) {
664			warn("warning: %s", path);
665			return (NULL);
666		}
667		return (obpath);
668	}
669
670	return (NULL);
671}
672
673/**
674 * In lieu of a good way to prevent every possible looping in make(1), stop
675 * there from being more than MKLVL_MAXVAL processes forked by make(1), to
676 * prevent a forkbomb from happening, in a dumb and mechanical way.
677 *
678 * Side Effects:
679 *	Creates or modifies enviornment variable MKLVL_ENVVAR via setenv().
680 */
681static void
682check_make_level(void)
683{
684#ifdef WANT_ENV_MKLVL
685	char	*value = getenv(MKLVL_ENVVAR);
686	int	level = (value == NULL) ? 0 : atoi(value);
687
688	if (level < 0) {
689		errx(2, "Invalid value for recursion level (%d).", level);
690	} else if (level > MKLVL_MAXVAL) {
691		errx(2, "Max recursion level (%d) exceeded.", MKLVL_MAXVAL);
692	} else {
693		char new_value[32];
694		sprintf(new_value, "%d", level + 1);
695		setenv(MKLVL_ENVVAR, new_value, 1);
696	}
697#endif /* WANT_ENV_MKLVL */
698}
699
700/**
701 * Main_AddSourceMakefile
702 *	Add a file to the list of source makefiles
703 */
704void
705Main_AddSourceMakefile(const char *name)
706{
707
708	Lst_AtEnd(&source_makefiles, estrdup(name));
709}
710
711/**
712 * Remake_Makefiles
713 *	Remake all the makefiles
714 */
715static void
716Remake_Makefiles(void)
717{
718	Lst cleanup;
719	LstNode *ln;
720	int error_cnt = 0;
721	int remade_cnt = 0;
722
723	Compat_InstallSignalHandlers();
724	if (curdir != objdir) {
725		if (chdir(curdir) < 0)
726			Fatal("Failed to change directory to %s.", curdir);
727	}
728
729	Lst_Init(&cleanup);
730	LST_FOREACH(ln, &source_makefiles) {
731		LstNode *ln2;
732		struct GNode *gn;
733		const char *name = Lst_Datum(ln);
734		Boolean saveTouchFlag = touchFlag;
735		Boolean saveQueryFlag = queryFlag;
736		Boolean saveNoExecute = noExecute;
737		int mtime;
738
739		/*
740		 * Create node
741		 */
742		gn = Targ_FindNode(name, TARG_CREATE);
743		DEBUGF(MAKE, ("Checking %s...", gn->name));
744		Suff_FindDeps(gn);
745
746		/*
747		 * -t, -q and -n has no effect unless the makefile is
748		 * specified as one of the targets explicitly in the
749		 * command line
750		 */
751		LST_FOREACH(ln2, &create) {
752			if (!strcmp(gn->name, Lst_Datum(ln2))) {
753				/* found as a target */
754				break;
755			}
756		}
757		if (ln2 == NULL) {
758			touchFlag = FALSE;
759			queryFlag = FALSE;
760			noExecute = FALSE;
761		}
762
763		/*
764		 * Check and remake the makefile
765		 */
766		mtime = Dir_MTime(gn);
767		remakingMakefiles = TRUE;
768		Compat_Make(gn, gn);
769		remakingMakefiles = FALSE;
770
771		/*
772		 * Restore -t, -q and -n behaviour
773		 */
774		touchFlag = saveTouchFlag;
775		queryFlag = saveQueryFlag;
776		noExecute = saveNoExecute;
777
778		/*
779		 * Compat_Make will leave the 'made' field of gn
780		 * in one of the following states:
781		 *	UPTODATE  gn was already up-to-date
782		 *	MADE	  gn was recreated successfully
783		 *	ERROR	  An error occurred while gn was being created
784		 *	ABORTED	  gn was not remade because one of its inferiors
785		 *		  could not be made due to errors.
786		 */
787		if (gn->made == MADE) {
788			if (mtime != Dir_MTime(gn)) {
789				DEBUGF(MAKE,
790				    ("%s updated (%d -> %d).\n",
791				     gn->name, mtime, gn->mtime));
792				remade_cnt++;
793			} else {
794				DEBUGF(MAKE,
795				    ("%s not updated: skipping restart.\n",
796				     gn->name));
797			}
798		} else if (gn->made == ERROR)
799			error_cnt++;
800		else if (gn->made == ABORTED) {
801			printf("`%s' not remade because of errors.\n",
802			    gn->name);
803			error_cnt++;
804		} else if (gn->made == UPTODATE) {
805			Lst_EnQueue(&cleanup, gn);
806		}
807	}
808
809	if (error_cnt > 0)
810		Fatal("Failed to remake Makefiles.");
811	if (remade_cnt > 0) {
812		DEBUGF(MAKE, ("Restarting `%s'.\n", save_argv[0]));
813
814		/*
815		 * Some of makefiles were remade -- restart from clean state
816		 */
817		if (save_makeflags != NULL)
818			setenv("MAKEFLAGS", save_makeflags, 1);
819		else
820			unsetenv("MAKEFLAGS");
821		if (execvp(save_argv[0], save_argv) < 0) {
822			Fatal("Can't restart `%s': %s.",
823			    save_argv[0], strerror(errno));
824		}
825	}
826
827	while (!Lst_IsEmpty(&cleanup)) {
828		GNode *gn = Lst_DeQueue(&cleanup);
829
830		gn->unmade = 0;
831		gn->make = FALSE;
832		gn->made = UNMADE;
833		gn->childMade = FALSE;
834		gn->mtime = gn->cmtime = 0;
835		gn->cmtime_gn = NULL;
836
837		LST_FOREACH(ln, &gn->children) {
838			GNode *cgn = Lst_Datum(ln);
839
840			gn->unmade++;
841			Lst_EnQueue(&cleanup, cgn);
842		}
843	}
844
845	if (curdir != objdir) {
846		if (chdir(objdir) < 0)
847			Fatal("Failed to change directory to %s.", objdir);
848	}
849}
850
851/**
852 * main
853 *	The main function, for obvious reasons. Initializes variables
854 *	and a few modules, then parses the arguments give it in the
855 *	environment and on the command line. Reads the system makefile
856 *	followed by either Makefile, makefile or the file given by the
857 *	-f argument. Sets the .MAKEFLAGS PMake variable based on all the
858 *	flags it has received by then uses either the Make or the Compat
859 *	module to create the initial list of targets.
860 *
861 * Results:
862 *	If -q was given, exits -1 if anything was out-of-date. Else it exits
863 *	0.
864 *
865 * Side Effects:
866 *	The program exits when done. Targets are created. etc. etc. etc.
867 */
868int
869main(int argc, char **argv)
870{
871	const char *machine;
872	const char *machine_arch;
873	const char *machine_cpu;
874	Boolean outOfDate = TRUE;	/* FALSE if all targets up to date */
875	const char *p;
876	const char *pathp;
877	const char *path;
878	char mdpath[MAXPATHLEN];
879	char obpath[MAXPATHLEN];
880	char cdpath[MAXPATHLEN];
881	char found_dir[MAXPATHLEN + 1];	/* for searching for sys.mk */
882	char *cp = NULL, *start;
883
884	save_argv = argv;
885	save_makeflags = getenv("MAKEFLAGS");
886	if (save_makeflags != NULL)
887		save_makeflags = estrdup(save_makeflags);
888
889	/*
890	 * Initialize file global variables.
891	 */
892	expandVars = TRUE;
893	noBuiltins = FALSE;		/* Read the built-in rules */
894	forceJobs = FALSE;		/* No -j flag */
895	curdir = cdpath;
896
897	/*
898	 * Initialize program global variables.
899	 */
900	beSilent = FALSE;		/* Print commands as executed */
901	ignoreErrors = FALSE;		/* Pay attention to non-zero returns */
902	noExecute = FALSE;		/* Execute all commands */
903	printGraphOnly = FALSE;		/* Don't stop after printing graph */
904	keepgoing = FALSE;		/* Stop on error */
905	allPrecious = FALSE;		/* Remove targets when interrupted */
906	queryFlag = FALSE;		/* This is not just a check-run */
907	touchFlag = FALSE;		/* Actually update targets */
908	usePipes = TRUE;		/* Catch child output in pipes */
909	debug = 0;			/* No debug verbosity, please. */
910	jobsRunning = FALSE;
911
912	jobLimit = DEFMAXJOBS;
913	compatMake = FALSE;		/* No compat mode */
914
915	check_make_level();
916
917#ifdef RLIMIT_NOFILE
918	/*
919	 * get rid of resource limit on file descriptors
920	 */
921	{
922		struct rlimit rl;
923		if (getrlimit(RLIMIT_NOFILE, &rl) == -1) {
924			err(2, "getrlimit");
925		}
926		rl.rlim_cur = rl.rlim_max;
927		if (setrlimit(RLIMIT_NOFILE, &rl) == -1) {
928			err(2, "setrlimit");
929		}
930	}
931#endif
932
933	/*
934	 * Prior to 7.0, FreeBSD/pc98 kernel used to set the
935	 * utsname.machine to "i386", and MACHINE was defined as
936	 * "i386", so it could not be distinguished from FreeBSD/i386.
937	 * Therefore, we had to check machine.ispc98 and adjust the
938	 * MACHINE variable.  NOTE: The code is still here to be able
939	 * to compile new make binary on old FreeBSD/pc98 systems, and
940	 * have the MACHINE variable set properly.
941	 */
942	if ((machine = getenv("MACHINE")) == NULL) {
943		int	ispc98;
944		size_t	len;
945
946		len = sizeof(ispc98);
947		if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
948			if (ispc98)
949				machine = "pc98";
950		}
951	}
952
953	/*
954	 * Get the name of this type of MACHINE from utsname
955	 * so we can share an executable for similar machines.
956	 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
957	 *
958	 * Note that both MACHINE and MACHINE_ARCH are decided at
959	 * run-time.
960	 */
961	if (machine == NULL) {
962		static struct utsname utsname;
963
964		if (uname(&utsname) == -1)
965			err(2, "uname");
966		machine = utsname.machine;
967	}
968
969	if ((machine_arch = getenv("MACHINE_ARCH")) == NULL) {
970#ifdef MACHINE_ARCH
971		machine_arch = MACHINE_ARCH;
972#else
973		machine_arch = "unknown";
974#endif
975	}
976
977	/*
978	 * Set machine_cpu to the minumum supported CPU revision based
979	 * on the target architecture, if not already set.
980	 */
981	if ((machine_cpu = getenv("MACHINE_CPU")) == NULL) {
982		if (!strcmp(machine_arch, "i386"))
983			machine_cpu = "i386";
984		else
985			machine_cpu = "unknown";
986	}
987
988	/*
989	 * Initialize the parsing, directory and variable modules to prepare
990	 * for the reading of inclusion paths and variable settings on the
991	 * command line
992	 */
993	Proc_Init();
994
995	Dir_Init();		/* Initialize directory structures so -I flags
996				 * can be processed correctly */
997	Var_Init(environ);	/* As well as the lists of variables for
998				 * parsing arguments */
999
1000	/*
1001	 * Initialize the Shell so that we have a shell for != assignments
1002	 * on the command line.
1003	 */
1004	Shell_Init();
1005
1006	/*
1007	 * Initialize various variables.
1008	 *	MAKE also gets this name, for compatibility
1009	 *	.MAKEFLAGS gets set to the empty string just in case.
1010	 *	MFLAGS also gets initialized empty, for compatibility.
1011	 */
1012	Var_SetGlobal("MAKE", argv[0]);
1013	Var_SetGlobal(".MAKEFLAGS", "");
1014	Var_SetGlobal("MFLAGS", "");
1015	Var_SetGlobal("MACHINE", machine);
1016	Var_SetGlobal("MACHINE_ARCH", machine_arch);
1017	Var_SetGlobal("MACHINE_CPU", machine_cpu);
1018#ifdef MAKE_VERSION
1019	Var_SetGlobal("MAKE_VERSION", MAKE_VERSION);
1020#endif
1021	Var_SetGlobal(".newline", "\n");	/* handy for :@ loops */
1022	{
1023		char tmp[64];
1024
1025		snprintf(tmp, sizeof(tmp), "%u", getpid());
1026		Var_SetGlobal(".MAKE.PID", tmp);
1027		snprintf(tmp, sizeof(tmp), "%u", getppid());
1028		Var_SetGlobal(".MAKE.PPID", tmp);
1029	}
1030	Job_SetPrefix();
1031
1032	/*
1033	 * Find where we are...
1034	 */
1035	if (getcwd(curdir, MAXPATHLEN) == NULL)
1036		err(2, NULL);
1037
1038	/*
1039	 * First snag things out of the MAKEFLAGS environment
1040	 * variable.  Then parse the command line arguments.
1041	 */
1042	Main_ParseArgLine(getenv("MAKEFLAGS"), 1);
1043
1044	MainParseArgs(argc, argv);
1045
1046	/*
1047	 * Verify that cwd is sane (after -C may have changed it).
1048	 */
1049	{
1050	struct stat sa;
1051
1052	if (stat(curdir, &sa) == -1)
1053	    err(2, "%s", curdir);
1054	}
1055
1056	/*
1057	 * The object directory location is determined using the
1058	 * following order of preference:
1059	 *
1060	 *	1. MAKEOBJDIRPREFIX`cwd`
1061	 *	2. MAKEOBJDIR
1062	 *	3. PATH_OBJDIR.${MACHINE}
1063	 *	4. PATH_OBJDIR
1064	 *	5. PATH_OBJDIRPREFIX`cwd`
1065	 *
1066	 * If one of the first two fails, use the current directory.
1067	 * If the remaining three all fail, use the current directory.
1068	 *
1069	 * Once things are initted,
1070	 * have to add the original directory to the search path,
1071	 * and modify the paths for the Makefiles apropriately.  The
1072	 * current directory is also placed as a variable for make scripts.
1073	 */
1074	if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
1075		if (!(path = getenv("MAKEOBJDIR"))) {
1076			path = PATH_OBJDIR;
1077			pathp = PATH_OBJDIRPREFIX;
1078			snprintf(mdpath, MAXPATHLEN, "%s.%s", path, machine);
1079			if (!(objdir = chdir_verify_path(mdpath, obpath)))
1080				if (!(objdir=chdir_verify_path(path, obpath))) {
1081					snprintf(mdpath, MAXPATHLEN,
1082							"%s%s", pathp, curdir);
1083					if (!(objdir=chdir_verify_path(mdpath,
1084								       obpath)))
1085						objdir = curdir;
1086				}
1087		}
1088		else if (!(objdir = chdir_verify_path(path, obpath)))
1089			objdir = curdir;
1090	}
1091	else {
1092		snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
1093		if (!(objdir = chdir_verify_path(mdpath, obpath)))
1094			objdir = curdir;
1095	}
1096	Dir_InitDot();		/* Initialize the "." directory */
1097	if (objdir != curdir)
1098		Path_AddDir(&dirSearchPath, curdir);
1099	Var_SetGlobal(".ST_EXPORTVAR", "YES");
1100	Var_SetGlobal(".CURDIR", curdir);
1101	Var_SetGlobal(".OBJDIR", objdir);
1102
1103	if (getenv("MAKE_JOBS_FIFO") != NULL)
1104		forceJobs = TRUE;
1105	/*
1106	 * Be compatible if user did not specify -j and did not explicitly
1107	 * turned compatibility on
1108	 */
1109	if (!compatMake && !forceJobs)
1110		compatMake = TRUE;
1111
1112	/*
1113	 * Initialize target and suffix modules in preparation for
1114	 * parsing the makefile(s)
1115	 */
1116	Targ_Init();
1117	Suff_Init();
1118
1119	DEFAULT = NULL;
1120	time(&now);
1121
1122	/*
1123	 * Set up the .TARGETS variable to contain the list of targets to be
1124	 * created. If none specified, make the variable empty -- the parser
1125	 * will fill the thing in with the default or .MAIN target.
1126	 */
1127	if (Lst_IsEmpty(&create)) {
1128		Var_SetGlobal(".TARGETS", "");
1129	} else {
1130		LstNode *ln;
1131
1132		for (ln = Lst_First(&create); ln != NULL; ln = Lst_Succ(ln)) {
1133			char *name = Lst_Datum(ln);
1134
1135			Var_Append(".TARGETS", name, VAR_GLOBAL);
1136		}
1137	}
1138
1139
1140	/*
1141	 * If no user-supplied system path was given (through the -m option)
1142	 * add the directories from the DEFSYSPATH (more than one may be given
1143	 * as dir1:...:dirn) to the system include path.
1144	 */
1145	if (TAILQ_EMPTY(&sysIncPath)) {
1146		char defsyspath[] = PATH_DEFSYSPATH;
1147		char *syspath = getenv("MAKESYSPATH");
1148
1149		/*
1150		 * If no user-supplied system path was given (thru -m option)
1151		 * add the directories from the DEFSYSPATH (more than one may
1152		 * be given as dir1:...:dirn) to the system include path.
1153		 */
1154		if (syspath == NULL || *syspath == '\0')
1155			syspath = defsyspath;
1156		else
1157			syspath = estrdup(syspath);
1158
1159		for (start = syspath; *start != '\0'; start = cp) {
1160			for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1161				continue;
1162			if (*cp == ':') {
1163				*cp++ = '\0';
1164			}
1165			/* look for magic parent directory search string */
1166			if (strncmp(".../", start, 4) == 0) {
1167				if (Dir_FindHereOrAbove(curdir, start + 4,
1168				    found_dir, sizeof(found_dir))) {
1169					Path_AddDir(&sysIncPath, found_dir);
1170				}
1171			} else {
1172				Path_AddDir(&sysIncPath, start);
1173			}
1174		}
1175		if (syspath != defsyspath)
1176			free(syspath);
1177	}
1178
1179	/*
1180	 * Read in the built-in rules first, followed by the specified
1181	 * makefile, if it was (makefile != (char *) NULL), or the default
1182	 * Makefile and makefile, in that order, if it wasn't.
1183	 */
1184	if (!noBuiltins) {
1185		/* Path of sys.mk */
1186		Lst sysMkPath = Lst_Initializer(sysMkPath);
1187		LstNode *ln;
1188		char	defsysmk[] = PATH_DEFSYSMK;
1189
1190		Path_Expand(defsysmk, &sysIncPath, &sysMkPath);
1191		if (Lst_IsEmpty(&sysMkPath))
1192			Fatal("make: no system rules (%s).", PATH_DEFSYSMK);
1193		LST_FOREACH(ln, &sysMkPath) {
1194			if (!ReadMakefile(Lst_Datum(ln)))
1195				break;
1196		}
1197		if (ln != NULL)
1198			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
1199		Lst_Destroy(&sysMkPath, free);
1200	}
1201
1202	if (!Lst_IsEmpty(&makefiles)) {
1203		LstNode *ln;
1204
1205		LST_FOREACH(ln, &makefiles) {
1206			if (!TryReadMakefile(Lst_Datum(ln)))
1207				break;
1208		}
1209		if (ln != NULL)
1210			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
1211	} else if (!TryReadMakefile("BSDmakefile"))
1212	    if (!TryReadMakefile("makefile"))
1213		TryReadMakefile("Makefile");
1214
1215	ReadMakefile(".depend");
1216
1217	/* Install all the flags into the MAKEFLAGS envariable. */
1218	if (((p = Var_Value(".MAKEFLAGS", VAR_GLOBAL)) != NULL) && *p)
1219		setenv("MAKEFLAGS", p, 1);
1220	else
1221		setenv("MAKEFLAGS", "", 1);
1222
1223	/*
1224	 * For compatibility, look at the directories in the VPATH variable
1225	 * and add them to the search path, if the variable is defined. The
1226	 * variable's value is in the same format as the PATH envariable, i.e.
1227	 * <directory>:<directory>:<directory>...
1228	 */
1229	if (Var_Exists("VPATH", VAR_CMD)) {
1230		/*
1231		 * GCC stores string constants in read-only memory, but
1232		 * Var_Subst will want to write this thing, so store it
1233		 * in an array
1234		 */
1235		static char VPATH[] = "${VPATH}";
1236		Buffer	*buf;
1237		char	*vpath;
1238		char	*ptr;
1239		char	savec;
1240
1241		buf = Var_Subst(VPATH, VAR_CMD, FALSE);
1242
1243		vpath = Buf_Data(buf);
1244		do {
1245			/* skip to end of directory */
1246			for (ptr = vpath; *ptr != ':' && *ptr != '\0'; ptr++)
1247				;
1248
1249			/* Save terminator character so know when to stop */
1250			savec = *ptr;
1251			*ptr = '\0';
1252
1253			/* Add directory to search path */
1254			Path_AddDir(&dirSearchPath, vpath);
1255
1256			vpath = ptr + 1;
1257		} while (savec != '\0');
1258
1259		Buf_Destroy(buf, TRUE);
1260	}
1261
1262	/*
1263	 * Now that all search paths have been read for suffixes et al, it's
1264	 * time to add the default search path to their lists...
1265	 */
1266	Suff_DoPaths();
1267
1268	/* print the initial graph, if the user requested it */
1269	if (DEBUG(GRAPH1))
1270		Targ_PrintGraph(1);
1271
1272	/* print the values of any variables requested by the user */
1273	if (Lst_IsEmpty(&variables) && !printGraphOnly) {
1274		/*
1275		 * Since the user has not requested that any variables
1276		 * be printed, we can build targets.
1277		 *
1278		 * Have read the entire graph and need to make a list of targets
1279		 * to create. If none was given on the command line, we consult
1280		 * the parsing module to find the main target(s) to create.
1281		 */
1282		Lst targs = Lst_Initializer(targs);
1283
1284		if (!is_posix && mfAutoDeps) {
1285			/*
1286			 * Check if any of the makefiles are out-of-date.
1287			 */
1288			Remake_Makefiles();
1289		}
1290
1291		if (Lst_IsEmpty(&create))
1292			Parse_MainName(&targs);
1293		else
1294			Targ_FindList(&targs, &create, TARG_CREATE);
1295
1296		if (compatMake) {
1297			/*
1298			 * Compat_Init will take care of creating
1299			 * all the targets as well as initializing
1300			 * the module.
1301			 */
1302			Compat_Run(&targs);
1303			outOfDate = 0;
1304		} else {
1305			/*
1306			 * Initialize job module before traversing
1307			 * the graph, now that any .BEGIN and .END
1308			 * targets have been read.  This is done
1309			 * only if the -q flag wasn't given (to
1310			 * prevent the .BEGIN from being executed
1311			 * should it exist).
1312			 */
1313			if (!queryFlag) {
1314				Job_Init(jobLimit);
1315				jobsRunning = TRUE;
1316			}
1317
1318			/* Traverse the graph, checking on all the targets */
1319			outOfDate = Make_Run(&targs);
1320		}
1321		Lst_Destroy(&targs, NOFREE);
1322
1323	} else {
1324		Var_Print(&variables, expandVars);
1325	}
1326
1327	Lst_Destroy(&variables, free);
1328	Lst_Destroy(&makefiles, free);
1329	Lst_Destroy(&source_makefiles, free);
1330	Lst_Destroy(&create, free);
1331
1332	/* print the graph now it's been processed if the user requested it */
1333	if (DEBUG(GRAPH2))
1334		Targ_PrintGraph(2);
1335
1336	if (queryFlag)
1337		return (outOfDate);
1338
1339	if (makeErrors != 0)
1340		Finish(makeErrors);
1341
1342	return (0);
1343}
1344