main.c revision 104696
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 104696 2002-10-09 03:42:10Z jmallett $");
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	Takes a line of arguments, breaks them and
58 *				treats them as if they were given when first
59 *				invoked. Used by the parse module to implement
60 *				the .MFLAGS target.
61 *
62 *	Error			Print a tagged error message. The global
63 *				MAKE variable must have been defined. This
64 *				takes a format string and two optional
65 *				arguments for it.
66 *
67 *	Fatal			Print an error message and exit. Also takes
68 *				a format string and two arguments.
69 *
70 *	Punt			Aborts all jobs and exits with a message. Also
71 *				takes a format string and two arguments.
72 *
73 *	Finish			Finish things up by printing the number of
74 *				errors which occured, as passed to it, and
75 *				exiting.
76 */
77
78#include <sys/types.h>
79#include <sys/time.h>
80#include <sys/param.h>
81#include <sys/resource.h>
82#include <sys/signal.h>
83#include <sys/stat.h>
84#if defined(__i386__)
85#include <sys/sysctl.h>
86#endif
87#ifndef MACHINE
88#include <sys/utsname.h>
89#endif
90#include <sys/wait.h>
91#include <err.h>
92#include <stdlib.h>
93#include <errno.h>
94#include <fcntl.h>
95#include <stdio.h>
96#include <sysexits.h>
97#include <stdarg.h>
98#include <unistd.h>
99#include "make.h"
100#include "hash.h"
101#include "dir.h"
102#include "job.h"
103#include "pathnames.h"
104
105#define WANT_ENV_MKLVL	1
106
107#ifndef	DEFMAXLOCAL
108#define	DEFMAXLOCAL DEFMAXJOBS
109#endif	/* DEFMAXLOCAL */
110
111#define	MAKEFLAGS	".MAKEFLAGS"
112
113Lst			create;		/* Targets to be made */
114time_t			now;		/* Time at start of make */
115GNode			*DEFAULT;	/* .DEFAULT node */
116Boolean			allPrecious;	/* .PRECIOUS given on line by itself */
117
118static Boolean		noBuiltins;	/* -r flag */
119static Lst		makefiles;	/* ordered list of makefiles to read */
120static Boolean		expandVars;	/* fully expand printed variables */
121static Lst		variables;	/* list of variables to print */
122int			maxJobs;	/* -j argument */
123static Boolean          forceJobs;      /* -j argument given */
124static int		maxLocal;	/* -L argument */
125Boolean			compatMake;	/* -B argument */
126Boolean			debug;		/* -d flag */
127Boolean			noExecute;	/* -n flag */
128Boolean			keepgoing;	/* -k flag */
129Boolean			queryFlag;	/* -q flag */
130Boolean			touchFlag;	/* -t flag */
131Boolean			usePipes;	/* !-P flag */
132Boolean			ignoreErrors;	/* -i flag */
133Boolean			beSilent;	/* -s flag */
134Boolean			beVerbose;	/* -v flag */
135Boolean			oldVars;	/* variable substitution style */
136Boolean			checkEnvFirst;	/* -e flag */
137Lst			envFirstVars;	/* (-E) vars to override from env */
138static Boolean		jobsRunning;	/* TRUE if the jobs might be running */
139
140static void		MainParseArgs(int, char **);
141char *			chdir_verify_path(char *, char *);
142static int		ReadMakefile(void *, void *);
143static void		usage(void);
144
145static char *curdir;			/* startup directory */
146static char *objdir;			/* where we chdir'ed to */
147
148/*-
149 * MainParseArgs --
150 *	Parse a given argument vector. Called from main() and from
151 *	Main_ParseArgLine() when the .MAKEFLAGS target is used.
152 *
153 *	XXX: Deal with command line overriding .MAKEFLAGS in makefile
154 *
155 * Results:
156 *	None
157 *
158 * Side Effects:
159 *	Various global and local flags will be set depending on the flags
160 *	given
161 */
162static void
163MainParseArgs(int argc, char **argv)
164{
165	char *p;
166	int c;
167
168	optind = 1;	/* since we're called more than once */
169#ifdef REMOTE
170# define OPTFLAGS "BC:D:E:I:L:PSV:Xd:ef:ij:km:nqrstv"
171#else
172# define OPTFLAGS "BC:D:E:I:PSV:Xd:ef:ij:km:nqrstv"
173#endif
174rearg:	while((c = getopt(argc, argv, OPTFLAGS)) != -1) {
175		switch(c) {
176		case 'C':
177			chdir(optarg);
178			break;
179		case 'D':
180			Var_Set(optarg, "1", VAR_GLOBAL);
181			Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
182			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
183			break;
184		case 'I':
185			Parse_AddIncludeDir(optarg);
186			Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
187			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
188			break;
189		case 'V':
190			(void)Lst_AtEnd(variables, (void *)optarg);
191			Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
192			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
193			break;
194		case 'X':
195			expandVars = FALSE;
196			break;
197		case 'B':
198			compatMake = TRUE;
199			Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
200			break;
201#ifdef REMOTE
202		case 'L': {
203			char *endptr;
204
205			maxLocal = strtol(optarg, &endptr, 10);
206			if (maxLocal < 0 || *endptr != '\0') {
207				warnx("illegal number, -L argument -- %s",
208				    optarg);
209				usage();
210			}
211			Var_Append(MAKEFLAGS, "-L", VAR_GLOBAL);
212			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
213			break;
214		}
215#endif
216		case 'P':
217			usePipes = FALSE;
218			Var_Append(MAKEFLAGS, "-P", VAR_GLOBAL);
219			break;
220		case 'S':
221			keepgoing = FALSE;
222			Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
223			break;
224		case 'd': {
225			char *modules = optarg;
226
227			for (; *modules; ++modules)
228				switch (*modules) {
229				case 'A':
230					debug = ~0;
231					break;
232				case 'a':
233					debug |= DEBUG_ARCH;
234					break;
235				case 'c':
236					debug |= DEBUG_COND;
237					break;
238				case 'd':
239					debug |= DEBUG_DIR;
240					break;
241				case 'f':
242					debug |= DEBUG_FOR;
243					break;
244				case 'g':
245					if (modules[1] == '1') {
246						debug |= DEBUG_GRAPH1;
247						++modules;
248					}
249					else if (modules[1] == '2') {
250						debug |= DEBUG_GRAPH2;
251						++modules;
252					}
253					break;
254				case 'j':
255					debug |= DEBUG_JOB;
256					break;
257				case 'l':
258					debug |= DEBUG_LOUD;
259					break;
260				case 'm':
261					debug |= DEBUG_MAKE;
262					break;
263				case 's':
264					debug |= DEBUG_SUFF;
265					break;
266				case 't':
267					debug |= DEBUG_TARG;
268					break;
269				case 'v':
270					debug |= DEBUG_VAR;
271					break;
272				default:
273					warnx("illegal argument to d option -- %c", *modules);
274					usage();
275				}
276			Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
277			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
278			break;
279		}
280		case 'E':
281			p = emalloc(strlen(optarg) + 1);
282			(void)strcpy(p, optarg);
283			(void)Lst_AtEnd(envFirstVars, (void *)p);
284			Var_Append(MAKEFLAGS, "-E", VAR_GLOBAL);
285			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
286			break;
287		case 'e':
288			checkEnvFirst = TRUE;
289			Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
290			break;
291		case 'f':
292			(void)Lst_AtEnd(makefiles, (void *)optarg);
293			break;
294		case 'i':
295			ignoreErrors = TRUE;
296			Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
297			break;
298		case 'j': {
299			char *endptr;
300
301			forceJobs = TRUE;
302			maxJobs = strtol(optarg, &endptr, 10);
303			if (maxJobs <= 0 || *endptr != '\0') {
304				warnx("illegal number, -j argument -- %s",
305				    optarg);
306				usage();
307			}
308#ifndef REMOTE
309			maxLocal = maxJobs;
310#endif
311			Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
312			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
313			break;
314		}
315		case 'k':
316			keepgoing = TRUE;
317			Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
318			break;
319		case 'm':
320			Dir_AddDir(sysIncPath, optarg);
321			Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
322			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
323			break;
324		case 'n':
325			noExecute = TRUE;
326			Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
327			break;
328		case 'q':
329			queryFlag = TRUE;
330			/* Kind of nonsensical, wot? */
331			Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
332			break;
333		case 'r':
334			noBuiltins = TRUE;
335			Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
336			break;
337		case 's':
338			beSilent = TRUE;
339			Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
340			break;
341		case 't':
342			touchFlag = TRUE;
343			Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
344			break;
345		case 'v':
346			beVerbose = TRUE;
347			Var_Append(MAKEFLAGS, "-v", VAR_GLOBAL);
348			break;
349		default:
350		case '?':
351			usage();
352		}
353	}
354
355	oldVars = TRUE;
356
357	/*
358	 * See if the rest of the arguments are variable assignments and
359	 * perform them if so. Else take them to be targets and stuff them
360	 * on the end of the "create" list.
361	 */
362	for (argv += optind, argc -= optind; *argv; ++argv, --argc)
363		if (Parse_IsVar(*argv))
364			Parse_DoVar(*argv, VAR_CMD);
365		else {
366			if (!**argv)
367				Punt("illegal (null) argument.");
368			if (**argv == '-') {
369				if ((*argv)[1])
370					optind = 0;     /* -flag... */
371				else
372					optind = 1;     /* - */
373				goto rearg;
374			}
375			(void)Lst_AtEnd(create, (void *)estrdup(*argv));
376		}
377}
378
379/*-
380 * Main_ParseArgLine --
381 *  	Used by the parse module when a .MFLAGS or .MAKEFLAGS target
382 *	is encountered and by main() when reading the .MAKEFLAGS envariable.
383 *	Takes a line of arguments and breaks it into its
384 * 	component words and passes those words and the number of them to the
385 *	MainParseArgs function.
386 *	The line should have all its leading whitespace removed.
387 *
388 * Results:
389 *	None
390 *
391 * Side Effects:
392 *	Only those that come from the various arguments.
393 */
394void
395Main_ParseArgLine(char *line)
396{
397	char **argv;			/* Manufactured argument vector */
398	int argc;			/* Number of arguments in argv */
399
400	if (line == NULL)
401		return;
402	for (; *line == ' '; ++line)
403		continue;
404	if (!*line)
405		return;
406
407	argv = brk_string(line, &argc, TRUE);
408	MainParseArgs(argc, argv);
409}
410
411char *
412chdir_verify_path(char *path, char *obpath)
413{
414	struct stat sb;
415
416	if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
417		if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) {
418			warn("warning: %s", path);
419			return 0;
420		}
421		return obpath;
422	}
423
424	return 0;
425}
426
427
428/*-
429 * main --
430 *	The main function, for obvious reasons. Initializes variables
431 *	and a few modules, then parses the arguments give it in the
432 *	environment and on the command line. Reads the system makefile
433 *	followed by either Makefile, makefile or the file given by the
434 *	-f argument. Sets the .MAKEFLAGS PMake variable based on all the
435 *	flags it has received by then uses either the Make or the Compat
436 *	module to create the initial list of targets.
437 *
438 * Results:
439 *	If -q was given, exits -1 if anything was out-of-date. Else it exits
440 *	0.
441 *
442 * Side Effects:
443 *	The program exits when done. Targets are created. etc. etc. etc.
444 */
445int
446main(int argc, char **argv)
447{
448	Lst targs;	/* target nodes to create -- passed to Make_Init */
449	Boolean outOfDate = TRUE; 	/* FALSE if all targets up to date */
450	struct stat sa;
451	char *p, *p1, *path, *pathp;
452#ifdef WANT_ENV_MKLVL
453#define	MKLVL_MAXVAL	500
454#define	MKLVL_ENVVAR	"__MKLVL__"
455	int iMkLvl = 0;
456	char *szMkLvl = getenv(MKLVL_ENVVAR);
457#endif	/* WANT_ENV_MKLVL */
458	char mdpath[MAXPATHLEN];
459	char obpath[MAXPATHLEN];
460	char cdpath[MAXPATHLEN];
461    	char *machine = getenv("MACHINE");
462	char *machine_arch = getenv("MACHINE_ARCH");
463	char *machine_cpu = getenv("MACHINE_CPU");
464	Lst sysMkPath;			/* Path of sys.mk */
465	char *cp = NULL, *start;
466					/* avoid faults on read-only strings */
467	static char syspath[] = _PATH_DEFSYSPATH;
468
469#ifdef WANT_ENV_MKLVL
470	if ((iMkLvl = szMkLvl ? atoi(szMkLvl) : 0) < 0) {
471	  iMkLvl = 0;
472	}
473	if (iMkLvl++ > MKLVL_MAXVAL) {
474	  errc(2, EAGAIN,
475	       "Max recursion level (%d) exceeded.", MKLVL_MAXVAL);
476	}
477	bzero(szMkLvl = emalloc(32), 32);
478	sprintf(szMkLvl, "%d", iMkLvl);
479	setenv(MKLVL_ENVVAR, szMkLvl, 1);
480#endif /* WANT_ENV_MKLVL */
481
482#if DEFSHELL == 2
483	/*
484	 * Turn off ENV to make ksh happier.
485	 */
486	unsetenv("ENV");
487#endif
488
489#ifdef RLIMIT_NOFILE
490	/*
491	 * get rid of resource limit on file descriptors
492	 */
493	{
494		struct rlimit rl;
495		if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
496		    rl.rlim_cur != rl.rlim_max) {
497			rl.rlim_cur = rl.rlim_max;
498			(void) setrlimit(RLIMIT_NOFILE, &rl);
499		}
500	}
501#endif
502	/*
503	 * Find where we are...
504	 * All this code is so that we know where we are when we start up
505	 * on a different machine with pmake.
506	 */
507	curdir = cdpath;
508	if (getcwd(curdir, MAXPATHLEN) == NULL)
509		err(2, NULL);
510
511	if (stat(curdir, &sa) == -1)
512	    err(2, "%s", curdir);
513
514#if defined(__i386__) && defined(__FreeBSD_version) && \
515    __FreeBSD_version > 300003
516	/*
517	 * PC-98 kernel sets the `i386' string to the utsname.machine and
518	 * it cannot be distinguished from IBM-PC by uname(3).  Therefore,
519	 * we check machine.ispc98 and adjust the machine variable before
520	 * using usname(3) below.
521	 * NOTE: machdep.ispc98 was defined on 1998/8/31. At that time,
522	 * __FreeBSD_version was defined as 300003. So, this check can
523	 * safely be done with any kernel with version > 300003.
524	 */
525	if (!machine) {
526		int	ispc98;
527		size_t	len;
528
529		len = sizeof(ispc98);
530		if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
531			if (ispc98)
532				machine = "pc98";
533		}
534	}
535#endif
536
537	/*
538	 * Get the name of this type of MACHINE from utsname
539	 * so we can share an executable for similar machines.
540	 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
541	 *
542	 * Note that while MACHINE is decided at run-time,
543	 * MACHINE_ARCH is always known at compile time.
544	 */
545	if (!machine) {
546#ifndef MACHINE
547	    struct utsname utsname;
548
549	    if (uname(&utsname) == -1)
550		    err(2, "uname");
551	    machine = utsname.machine;
552#else
553	    machine = MACHINE;
554#endif
555	}
556
557	if (!machine_arch) {
558#ifndef MACHINE_ARCH
559		machine_arch = "unknown";
560#else
561		machine_arch = MACHINE_ARCH;
562#endif
563	}
564
565	/*
566	 * Set machine_cpu to the minumum supported CPU revision based
567	 * on the target architecture, if not already set.
568	 */
569	if (!machine_cpu) {
570		if (!strcmp(machine_arch, "i386"))
571			machine_cpu = "i386";
572		else if (!strcmp(machine_arch, "alpha"))
573			machine_cpu = "ev4";
574		else
575			machine_cpu = "unknown";
576	}
577
578	/*
579	 * The object directory location is determined using the
580	 * following order of preference:
581	 *
582	 *	1. MAKEOBJDIRPREFIX`cwd`
583	 *	2. MAKEOBJDIR
584	 *	3. _PATH_OBJDIR.${MACHINE}
585	 *	4. _PATH_OBJDIR
586	 *	5. _PATH_OBJDIRPREFIX`cwd`
587	 *
588	 * If one of the first two fails, use the current directory.
589	 * If the remaining three all fail, use the current directory.
590	 *
591	 * Once things are initted,
592	 * have to add the original directory to the search path,
593	 * and modify the paths for the Makefiles apropriately.  The
594	 * current directory is also placed as a variable for make scripts.
595	 */
596	if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
597		if (!(path = getenv("MAKEOBJDIR"))) {
598			path = _PATH_OBJDIR;
599			pathp = _PATH_OBJDIRPREFIX;
600			(void) snprintf(mdpath, MAXPATHLEN, "%s.%s",
601					path, machine);
602			if (!(objdir = chdir_verify_path(mdpath, obpath)))
603				if (!(objdir=chdir_verify_path(path, obpath))) {
604					(void) snprintf(mdpath, MAXPATHLEN,
605							"%s%s", pathp, curdir);
606					if (!(objdir=chdir_verify_path(mdpath,
607								       obpath)))
608						objdir = curdir;
609				}
610		}
611		else if (!(objdir = chdir_verify_path(path, obpath)))
612			objdir = curdir;
613	}
614	else {
615		(void) snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
616		if (!(objdir = chdir_verify_path(mdpath, obpath)))
617			objdir = curdir;
618	}
619
620	create = Lst_Init(FALSE);
621	makefiles = Lst_Init(FALSE);
622	envFirstVars = Lst_Init(FALSE);
623	expandVars = TRUE;
624	variables = Lst_Init(FALSE);
625	beSilent = FALSE;		/* Print commands as executed */
626	ignoreErrors = FALSE;		/* Pay attention to non-zero returns */
627	noExecute = FALSE;		/* Execute all commands */
628	keepgoing = FALSE;		/* Stop on error */
629	allPrecious = FALSE;		/* Remove targets when interrupted */
630	queryFlag = FALSE;		/* This is not just a check-run */
631	noBuiltins = FALSE;		/* Read the built-in rules */
632	touchFlag = FALSE;		/* Actually update targets */
633	usePipes = TRUE;		/* Catch child output in pipes */
634	debug = 0;			/* No debug verbosity, please. */
635	jobsRunning = FALSE;
636
637	maxLocal = DEFMAXLOCAL;		/* Set default local max concurrency */
638#ifdef REMOTE
639	maxJobs = DEFMAXJOBS;		/* Set default max concurrency */
640#else
641	maxJobs = maxLocal;
642#endif
643	forceJobs = FALSE;              /* No -j flag */
644	compatMake = FALSE;		/* No compat mode */
645
646
647	/*
648	 * Initialize the parsing, directory and variable modules to prepare
649	 * for the reading of inclusion paths and variable settings on the
650	 * command line
651	 */
652	Dir_Init();		/* Initialize directory structures so -I flags
653				 * can be processed correctly */
654	Parse_Init();		/* Need to initialize the paths of #include
655				 * directories */
656	Var_Init();		/* As well as the lists of variables for
657				 * parsing arguments */
658        str_init();
659	if (objdir != curdir)
660		Dir_AddDir(dirSearchPath, curdir);
661	Var_Set(".CURDIR", curdir, VAR_GLOBAL);
662	Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
663
664	/*
665	 * Initialize various variables.
666	 *	MAKE also gets this name, for compatibility
667	 *	.MAKEFLAGS gets set to the empty string just in case.
668	 *	MFLAGS also gets initialized empty, for compatibility.
669	 */
670	Var_Set("MAKE", argv[0], VAR_GLOBAL);
671	Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
672	Var_Set("MFLAGS", "", VAR_GLOBAL);
673	Var_Set("MACHINE", machine, VAR_GLOBAL);
674	Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
675	Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
676#ifdef MAKE_VERSION
677	Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
678#endif
679
680	/*
681	 * First snag any flags out of the MAKE environment variable.
682	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
683	 * in a different format).
684	 */
685#ifdef POSIX
686	Main_ParseArgLine(getenv("MAKEFLAGS"));
687#else
688	Main_ParseArgLine(getenv("MAKE"));
689#endif
690
691	MainParseArgs(argc, argv);
692
693	/*
694	 * Be compatible if user did not specify -j and did not explicitly
695	 * turned compatibility on
696	 */
697	if (!compatMake && !forceJobs)
698		compatMake = TRUE;
699
700	/*
701	 * Initialize archive, target and suffix modules in preparation for
702	 * parsing the makefile(s)
703	 */
704	Arch_Init();
705	Targ_Init();
706	Suff_Init();
707
708	DEFAULT = NULL;
709	(void)time(&now);
710
711	/*
712	 * Set up the .TARGETS variable to contain the list of targets to be
713	 * created. If none specified, make the variable empty -- the parser
714	 * will fill the thing in with the default or .MAIN target.
715	 */
716	if (!Lst_IsEmpty(create)) {
717		LstNode ln;
718
719		for (ln = Lst_First(create); ln != NULL;
720		    ln = Lst_Succ(ln)) {
721			char *name = (char *)Lst_Datum(ln);
722
723			Var_Append(".TARGETS", name, VAR_GLOBAL);
724		}
725	} else
726		Var_Set(".TARGETS", "", VAR_GLOBAL);
727
728
729	/*
730	 * If no user-supplied system path was given (through the -m option)
731	 * add the directories from the DEFSYSPATH (more than one may be given
732	 * as dir1:...:dirn) to the system include path.
733	 */
734	if (Lst_IsEmpty(sysIncPath)) {
735		for (start = syspath; *start != '\0'; start = cp) {
736			for (cp = start; *cp != '\0' && *cp != ':'; cp++)
737				continue;
738			if (*cp == '\0') {
739				Dir_AddDir(sysIncPath, start);
740			} else {
741				*cp++ = '\0';
742				Dir_AddDir(sysIncPath, start);
743			}
744		}
745	}
746
747	/*
748	 * Read in the built-in rules first, followed by the specified
749	 * makefile, if it was (makefile != (char *) NULL), or the default
750	 * Makefile and makefile, in that order, if it wasn't.
751	 */
752	if (!noBuiltins) {
753		LstNode ln;
754
755		sysMkPath = Lst_Init (FALSE);
756		Dir_Expand (_PATH_DEFSYSMK, sysIncPath, sysMkPath);
757		if (Lst_IsEmpty(sysMkPath))
758			Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
759		ln = Lst_Find(sysMkPath, (void *)NULL, ReadMakefile);
760		if (ln != NULL)
761			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
762	}
763
764	if (!Lst_IsEmpty(makefiles)) {
765		LstNode ln;
766
767		ln = Lst_Find(makefiles, (void *)NULL, ReadMakefile);
768		if (ln != NULL)
769			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
770	} else if (!ReadMakefile("BSDmakefile", NULL))
771	    if (!ReadMakefile("makefile", NULL))
772		(void)ReadMakefile("Makefile", NULL);
773
774	(void)ReadMakefile(".depend", NULL);
775
776	Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
777	efree(p1);
778
779	/* Install all the flags into the MAKE envariable. */
780	if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
781#ifdef POSIX
782		setenv("MAKEFLAGS", p, 1);
783#else
784		setenv("MAKE", p, 1);
785#endif
786	efree(p1);
787
788	/*
789	 * For compatibility, look at the directories in the VPATH variable
790	 * and add them to the search path, if the variable is defined. The
791	 * variable's value is in the same format as the PATH envariable, i.e.
792	 * <directory>:<directory>:<directory>...
793	 */
794	if (Var_Exists("VPATH", VAR_CMD)) {
795		char *vpath, savec;
796		/*
797		 * GCC stores string constants in read-only memory, but
798		 * Var_Subst will want to write this thing, so store it
799		 * in an array
800		 */
801		static char VPATH[] = "${VPATH}";
802
803		vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
804		path = vpath;
805		do {
806			/* skip to end of directory */
807			for (cp = path; *cp != ':' && *cp != '\0'; cp++)
808				continue;
809			/* Save terminator character so know when to stop */
810			savec = *cp;
811			*cp = '\0';
812			/* Add directory to search path */
813			Dir_AddDir(dirSearchPath, path);
814			*cp = savec;
815			path = cp + 1;
816		} while (savec == ':');
817		(void)free(vpath);
818	}
819
820	/*
821	 * Now that all search paths have been read for suffixes et al, it's
822	 * time to add the default search path to their lists...
823	 */
824	Suff_DoPaths();
825
826	/* print the initial graph, if the user requested it */
827	if (DEBUG(GRAPH1))
828		Targ_PrintGraph(1);
829
830	/* print the values of any variables requested by the user */
831	if (!Lst_IsEmpty(variables)) {
832		LstNode ln;
833
834		for (ln = Lst_First(variables); ln != NULL;
835		    ln = Lst_Succ(ln)) {
836			char *value;
837			if (expandVars) {
838				p1 = emalloc(strlen((char *)Lst_Datum(ln)) + 1 + 3);
839				/* This sprintf is safe, because of the malloc above */
840				(void)sprintf(p1, "${%s}", (char *)Lst_Datum(ln));
841				value = Var_Subst(NULL, p1, VAR_GLOBAL, FALSE);
842			} else {
843				value = Var_Value((char *)Lst_Datum(ln),
844						  VAR_GLOBAL, &p1);
845			}
846			printf("%s\n", value ? value : "");
847			if (p1)
848				free(p1);
849		}
850	} else {
851
852		/*
853		 * Have now read the entire graph and need to make a list of targets
854		 * to create. If none was given on the command line, we consult the
855		 * parsing module to find the main target(s) to create.
856		 */
857		if (Lst_IsEmpty(create))
858			targs = Parse_MainName();
859		else
860			targs = Targ_FindList(create, TARG_CREATE);
861
862		if (!compatMake) {
863			/*
864			 * Initialize job module before traversing the graph, now that
865			 * any .BEGIN and .END targets have been read.  This is done
866			 * only if the -q flag wasn't given (to prevent the .BEGIN from
867			 * being executed should it exist).
868			 */
869			if (!queryFlag) {
870				if (maxLocal == -1)
871					maxLocal = maxJobs;
872				Job_Init(maxJobs, maxLocal);
873				jobsRunning = TRUE;
874			}
875
876			/* Traverse the graph, checking on all the targets */
877			outOfDate = Make_Run(targs);
878		} else {
879			/*
880			 * Compat_Init will take care of creating all the targets as
881			 * well as initializing the module.
882			 */
883			Compat_Run(targs);
884		}
885		Lst_Destroy(targs, NOFREE);
886	}
887
888	Lst_Destroy(variables, NOFREE);
889	Lst_Destroy(makefiles, NOFREE);
890	Lst_Destroy(create, (void (*)(void *)) free);
891
892	/* print the graph now it's been processed if the user requested it */
893	if (DEBUG(GRAPH2))
894		Targ_PrintGraph(2);
895
896	Suff_End();
897        Targ_End();
898	Arch_End();
899	str_end();
900	Var_End();
901	Parse_End();
902	Dir_End();
903
904	if (queryFlag && outOfDate)
905		return(1);
906	else
907		return(0);
908}
909
910/*-
911 * ReadMakefile  --
912 *	Open and parse the given makefile.
913 *
914 * Results:
915 *	TRUE if ok. FALSE if couldn't open file.
916 *
917 * Side Effects:
918 *	lots
919 */
920static Boolean
921ReadMakefile(void *p, void *q __unused)
922{
923	char *fname;			/* makefile to read */
924	FILE *stream;
925	char *name, path[MAXPATHLEN];
926	char *MAKEFILE;
927	int setMAKEFILE;
928
929	fname = p;
930
931	if (!strcmp(fname, "-")) {
932		Parse_File("(stdin)", stdin);
933		Var_Set("MAKEFILE", "", VAR_GLOBAL);
934	} else {
935		setMAKEFILE = strcmp(fname, ".depend");
936
937		/* if we've chdir'd, rebuild the path name */
938		if (curdir != objdir && *fname != '/') {
939			(void)snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
940			/*
941			 * XXX The realpath stuff breaks relative includes
942			 * XXX in some cases.   The problem likely is in
943			 * XXX parse.c where it does special things in
944			 * XXX ParseDoInclude if the file is relateive
945			 * XXX or absolute and not a system file.  There
946			 * XXX it assumes that if the current file that's
947			 * XXX being included is absolute, that any files
948			 * XXX that it includes shouldn't do the -I path
949			 * XXX stuff, which is inconsistant with historical
950			 * XXX behavior.  However, I can't pentrate the mists
951			 * XXX further, so I'm putting this workaround in
952			 * XXX here until such time as the underlying bug
953			 * XXX can be fixed.
954			 */
955#if THIS_BREAKS_THINGS
956			if (realpath(path, path) != NULL &&
957			    (stream = fopen(path, "r")) != NULL) {
958				MAKEFILE = fname;
959				fname = path;
960				goto found;
961			}
962		} else if (realpath(fname, path) != NULL) {
963			MAKEFILE = fname;
964			fname = path;
965			if ((stream = fopen(fname, "r")) != NULL)
966				goto found;
967		}
968#else
969			if ((stream = fopen(path, "r")) != NULL) {
970				MAKEFILE = fname;
971				fname = path;
972				goto found;
973			}
974		} else {
975			MAKEFILE = fname;
976			if ((stream = fopen(fname, "r")) != NULL)
977				goto found;
978		}
979#endif
980		/* look in -I and system include directories. */
981		name = Dir_FindFile(fname, parseIncPath);
982		if (!name)
983			name = Dir_FindFile(fname, sysIncPath);
984		if (!name || !(stream = fopen(name, "r")))
985			return(FALSE);
986		MAKEFILE = fname = name;
987		/*
988		 * set the MAKEFILE variable desired by System V fans -- the
989		 * placement of the setting here means it gets set to the last
990		 * makefile specified, as it is set by SysV make.
991		 */
992found:
993		if (setMAKEFILE)
994			Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
995		Parse_File(fname, stream);
996		(void)fclose(stream);
997	}
998	return(TRUE);
999}
1000
1001/*-
1002 * Cmd_Exec --
1003 *	Execute the command in cmd, and return the output of that command
1004 *	in a string.
1005 *
1006 * Results:
1007 *	A string containing the output of the command, or the empty string
1008 *	If error is not NULL, it contains the reason for the command failure
1009 *
1010 * Side Effects:
1011 *	The string must be freed by the caller.
1012 */
1013char *
1014Cmd_Exec(char *cmd, char **error)
1015{
1016    char	*args[4];   	/* Args for invoking the shell */
1017    int 	fds[2];	    	/* Pipe streams */
1018    int 	cpid;	    	/* Child PID */
1019    int 	pid;	    	/* PID from wait() */
1020    char	*res;		/* result */
1021    int		status;		/* command exit status */
1022    Buffer	buf;		/* buffer to store the result */
1023    char	*cp;
1024    int		cc;
1025
1026    *error = NULL;
1027
1028    /*
1029     * Set up arguments for shell
1030     */
1031    args[0] = "sh";
1032    args[1] = "-c";
1033    args[2] = cmd;
1034    args[3] = NULL;
1035
1036    /*
1037     * Open a pipe for fetching its output
1038     */
1039    if (pipe(fds) == -1) {
1040	*error = "Couldn't create pipe for \"%s\"";
1041	goto bad;
1042    }
1043
1044    /*
1045     * Fork
1046     */
1047    switch (cpid = vfork()) {
1048    case 0:
1049	/*
1050	 * Close input side of pipe
1051	 */
1052	(void) close(fds[0]);
1053
1054	/*
1055	 * Duplicate the output stream to the shell's output, then
1056	 * shut the extra thing down. Note we don't fetch the error
1057	 * stream...why not? Why?
1058	 */
1059	(void) dup2(fds[1], 1);
1060	(void) close(fds[1]);
1061
1062#if defined(DEFSHELL) && DEFSHELL == 0
1063	(void) execv("/bin/csh", args);
1064#elif DEFSHELL == 1
1065	(void) execv("/bin/sh", args);
1066#elif DEFSHELL == 2
1067	(void) execv("/bin/ksh", args);
1068#else
1069#error "DEFSHELL must be 1 or 2."
1070#endif
1071	_exit(1);
1072	/*NOTREACHED*/
1073
1074    case -1:
1075	*error = "Couldn't exec \"%s\"";
1076	goto bad;
1077
1078    default:
1079	/*
1080	 * No need for the writing half
1081	 */
1082	(void) close(fds[1]);
1083
1084	buf = Buf_Init (MAKE_BSIZE);
1085
1086	do {
1087	    char   result[BUFSIZ];
1088	    cc = read(fds[0], result, sizeof(result));
1089	    if (cc > 0)
1090		Buf_AddBytes(buf, cc, (Byte *) result);
1091	}
1092	while (cc > 0 || (cc == -1 && errno == EINTR));
1093
1094	/*
1095	 * Close the input side of the pipe.
1096	 */
1097	(void) close(fds[0]);
1098
1099	/*
1100	 * Wait for the process to exit.
1101	 */
1102	while(((pid = wait(&status)) != cpid) && (pid >= 0))
1103	    continue;
1104
1105	if (cc == -1)
1106	    *error = "Error reading shell's output for \"%s\"";
1107
1108	res = (char *)Buf_GetAll (buf, &cc);
1109	Buf_Destroy (buf, FALSE);
1110
1111	if (status)
1112	    *error = "\"%s\" returned non-zero status";
1113
1114	/*
1115	 * Null-terminate the result, convert newlines to spaces and
1116	 * install it in the variable.
1117	 */
1118	res[cc] = '\0';
1119	cp = &res[cc] - 1;
1120
1121	if (*cp == '\n') {
1122	    /*
1123	     * A final newline is just stripped
1124	     */
1125	    *cp-- = '\0';
1126	}
1127	while (cp >= res) {
1128	    if (*cp == '\n') {
1129		*cp = ' ';
1130	    }
1131	    cp--;
1132	}
1133	break;
1134    }
1135    return res;
1136bad:
1137    res = emalloc(1);
1138    *res = '\0';
1139    return res;
1140}
1141
1142/*-
1143 * Debug --
1144 *	Print a debugging message given its format.
1145 *
1146 * Results:
1147 *	None.
1148 *
1149 * Side Effects:
1150 *	The message is printed.
1151 */
1152/* VARARGS */
1153void
1154Debug(const char *fmt, ...)
1155{
1156	va_list ap;
1157
1158	va_start(ap, fmt);
1159	(void)vfprintf(stderr, fmt, ap);
1160	va_end(ap);
1161	(void)fflush(stderr);
1162}
1163
1164/*-
1165 * Error --
1166 *	Print an error message given its format.
1167 *
1168 * Results:
1169 *	None.
1170 *
1171 * Side Effects:
1172 *	The message is printed.
1173 */
1174/* VARARGS */
1175void
1176Error(const char *fmt, ...)
1177{
1178	va_list ap;
1179
1180	va_start(ap, fmt);
1181	(void)vfprintf(stderr, fmt, ap);
1182	va_end(ap);
1183	(void)fprintf(stderr, "\n");
1184	(void)fflush(stderr);
1185}
1186
1187/*-
1188 * Fatal --
1189 *	Produce a Fatal error message. If jobs are running, waits for them
1190 *	to finish.
1191 *
1192 * Results:
1193 *	None
1194 *
1195 * Side Effects:
1196 *	The program exits
1197 */
1198/* VARARGS */
1199void
1200Fatal(const char *fmt, ...)
1201{
1202	va_list ap;
1203
1204	va_start(ap, fmt);
1205	if (jobsRunning)
1206		Job_Wait();
1207
1208	(void)vfprintf(stderr, fmt, ap);
1209	va_end(ap);
1210	(void)fprintf(stderr, "\n");
1211	(void)fflush(stderr);
1212
1213	if (DEBUG(GRAPH2))
1214		Targ_PrintGraph(2);
1215	exit(2);		/* Not 1 so -q can distinguish error */
1216}
1217
1218/*
1219 * Punt --
1220 *	Major exception once jobs are being created. Kills all jobs, prints
1221 *	a message and exits.
1222 *
1223 * Results:
1224 *	None
1225 *
1226 * Side Effects:
1227 *	All children are killed indiscriminately and the program Lib_Exits
1228 */
1229/* VARARGS */
1230void
1231Punt(const char *fmt, ...)
1232{
1233	va_list ap;
1234
1235	va_start(ap, fmt);
1236	(void)fprintf(stderr, "make: ");
1237	(void)vfprintf(stderr, fmt, ap);
1238	va_end(ap);
1239	(void)fprintf(stderr, "\n");
1240	(void)fflush(stderr);
1241
1242	DieHorribly();
1243}
1244
1245/*-
1246 * DieHorribly --
1247 *	Exit without giving a message.
1248 *
1249 * Results:
1250 *	None
1251 *
1252 * Side Effects:
1253 *	A big one...
1254 */
1255void
1256DieHorribly(void)
1257{
1258	if (jobsRunning)
1259		Job_AbortAll();
1260	if (DEBUG(GRAPH2))
1261		Targ_PrintGraph(2);
1262	exit(2);		/* Not 1, so -q can distinguish error */
1263}
1264
1265/*
1266 * Finish --
1267 *	Called when aborting due to errors in child shell to signal
1268 *	abnormal exit, with the number of errors encountered in Make_Make.
1269 *
1270 * Results:
1271 *	None
1272 *
1273 * Side Effects:
1274 *	The program exits
1275 */
1276void
1277Finish(int errors)
1278{
1279	Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1280}
1281
1282/*
1283 * emalloc --
1284 *	malloc, but die on error.
1285 */
1286void *
1287emalloc(size_t len)
1288{
1289	void *p;
1290
1291	if ((p = malloc(len)) == NULL)
1292		enomem();
1293	return(p);
1294}
1295
1296/*
1297 * estrdup --
1298 *	strdup, but die on error.
1299 */
1300char *
1301estrdup(const char *str)
1302{
1303	char *p;
1304
1305	if ((p = strdup(str)) == NULL)
1306		enomem();
1307	return(p);
1308}
1309
1310/*
1311 * erealloc --
1312 *	realloc, but die on error.
1313 */
1314void *
1315erealloc(void *ptr, size_t size)
1316{
1317	if ((ptr = realloc(ptr, size)) == NULL)
1318		enomem();
1319	return(ptr);
1320}
1321
1322/*
1323 * enomem --
1324 *	die when out of memory.
1325 */
1326void
1327enomem(void)
1328{
1329	err(2, NULL);
1330}
1331
1332/*
1333 * enunlink --
1334 *	Remove a file carefully, avoiding directories.
1335 */
1336int
1337eunlink(const char *file)
1338{
1339	struct stat st;
1340
1341	if (lstat(file, &st) == -1)
1342		return -1;
1343
1344	if (S_ISDIR(st.st_mode)) {
1345		errno = EISDIR;
1346		return -1;
1347	}
1348	return unlink(file);
1349}
1350
1351/*
1352 * usage --
1353 *	exit with usage message
1354 */
1355static void
1356usage(void)
1357{
1358	(void)fprintf(stderr, "%s\n%s\n%s\n",
1359"usage: make [-Beiknqrstv] [-D variable] [-d flags] [-E variable] [-f makefile]",
1360"            [-I directory] [-j max_jobs] [-m directory] [-V variable]",
1361"            [variable=value] [target ...]");
1362	exit(2);
1363}
1364
1365
1366int
1367PrintAddr(void *a, void *b __unused)
1368{
1369    printf("%p ", a);
1370    return 0;
1371}
1372