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