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