main.c revision 40500
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.26 1998/09/09 14:58:30 kato 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 sa;
438	char *p, *p1, *path, *pathp;
439#ifdef WANT_ENV_PWD
440	struct stat sb;
441	char *pwd;
442#endif
443	char mdpath[MAXPATHLEN + 1];
444	char obpath[MAXPATHLEN + 1];
445	char cdpath[MAXPATHLEN + 1];
446    	char *machine = getenv("MACHINE");
447	Lst sysMkPath;			/* Path of sys.mk */
448	char *cp = NULL, *start;
449					/* avoid faults on read-only strings */
450	static char syspath[] = _PATH_DEFSYSPATH;
451
452#ifdef RLIMIT_NOFILE
453	/*
454	 * get rid of resource limit on file descriptors
455	 */
456	{
457		struct rlimit rl;
458		if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
459		    rl.rlim_cur != rl.rlim_max) {
460			rl.rlim_cur = rl.rlim_max;
461			(void) setrlimit(RLIMIT_NOFILE, &rl);
462		}
463	}
464#endif
465	/*
466	 * Find where we are and take care of PWD for the automounter...
467	 * All this code is so that we know where we are when we start up
468	 * on a different machine with pmake.
469	 */
470	curdir = cdpath;
471	if (getcwd(curdir, MAXPATHLEN) == NULL)
472		err(2, NULL);
473
474	if (stat(curdir, &sa) == -1)
475	    err(2, "%s", curdir);
476
477#ifdef WANT_ENV_PWD
478	if ((pwd = getenv("PWD")) != NULL) {
479	    if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
480		sa.st_dev == sb.st_dev)
481		(void) strcpy(curdir, pwd);
482	}
483#endif
484
485#if defined(__i386__)
486	/*
487	 * PC-98 kernel sets the `i386' string to the utsname.machine and
488	 * it cannot be distinguished from IBM-PC by uname(3).  Therefore,
489	 * we check machine.ispc98 and adjust the machine variable before
490	 * using usname(3) below.
491	 */
492	if (!machine) {
493		int	ispc98;
494		size_t	len;
495
496		len = sizeof(ispc98);
497		if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
498			if (ispc98)
499				machine = "pc98";
500		}
501	}
502#endif
503
504	/*
505	 * Get the name of this type of MACHINE from utsname
506	 * so we can share an executable for similar machines.
507	 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
508	 *
509	 * Note that while MACHINE is decided at run-time,
510	 * MACHINE_ARCH is always known at compile time.
511	 */
512	if (!machine) {
513#ifndef MACHINE
514	    struct utsname utsname;
515
516	    if (uname(&utsname) == -1) {
517		    perror("make: uname");
518		    exit(2);
519	    }
520	    machine = utsname.machine;
521#else
522	    machine = MACHINE;
523#endif
524	}
525
526	/*
527	 * The object directory location is determined using the
528	 * following order of preference:
529	 *
530	 *	1. MAKEOBJDIRPREFIX`cwd`
531	 *	2. MAKEOBJDIR
532	 *	3. _PATH_OBJDIR.${MACHINE}
533	 *	4. _PATH_OBJDIR
534	 *	5. _PATH_OBJDIRPREFIX${MACHINE}
535	 *
536	 * If all fails, use the current directory to build.
537	 *
538	 * Once things are initted,
539	 * have to add the original directory to the search path,
540	 * and modify the paths for the Makefiles apropriately.  The
541	 * current directory is also placed as a variable for make scripts.
542	 */
543	if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
544		if (!(path = getenv("MAKEOBJDIR"))) {
545			path = _PATH_OBJDIR;
546			pathp = _PATH_OBJDIRPREFIX;
547			(void) snprintf(mdpath, MAXPATHLEN, "%s.%s",
548					path, machine);
549			if (!(objdir = chdir_verify_path(mdpath, obpath)))
550				if (!(objdir=chdir_verify_path(path, obpath))) {
551					(void) snprintf(mdpath, MAXPATHLEN,
552							"%s%s", pathp, curdir);
553					if (!(objdir=chdir_verify_path(mdpath,
554								       obpath)))
555						objdir = curdir;
556				}
557		}
558		else if (!(objdir = chdir_verify_path(path, obpath)))
559			objdir = curdir;
560	}
561	else {
562		(void) snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
563		if (!(objdir = chdir_verify_path(mdpath, obpath)))
564			objdir = curdir;
565	}
566
567#ifdef WANT_ENV_PWD
568	setenv("PWD", objdir, 1);
569#endif
570
571	create = Lst_Init(FALSE);
572	makefiles = Lst_Init(FALSE);
573	printVars = FALSE;
574	variables = Lst_Init(FALSE);
575	beSilent = FALSE;		/* Print commands as executed */
576	ignoreErrors = FALSE;		/* Pay attention to non-zero returns */
577	noExecute = FALSE;		/* Execute all commands */
578	keepgoing = FALSE;		/* Stop on error */
579	allPrecious = FALSE;		/* Remove targets when interrupted */
580	queryFlag = FALSE;		/* This is not just a check-run */
581	noBuiltins = FALSE;		/* Read the built-in rules */
582	touchFlag = FALSE;		/* Actually update targets */
583	usePipes = TRUE;		/* Catch child output in pipes */
584	debug = 0;			/* No debug verbosity, please. */
585	jobsRunning = FALSE;
586
587	maxLocal = DEFMAXLOCAL;		/* Set default local max concurrency */
588#ifdef REMOTE
589	maxJobs = DEFMAXJOBS;		/* Set default max concurrency */
590#else
591	maxJobs = maxLocal;
592#endif
593	forceJobs = FALSE;              /* No -j flag */
594	compatMake = FALSE;		/* No compat mode */
595
596
597	/*
598	 * Initialize the parsing, directory and variable modules to prepare
599	 * for the reading of inclusion paths and variable settings on the
600	 * command line
601	 */
602	Dir_Init();		/* Initialize directory structures so -I flags
603				 * can be processed correctly */
604	Parse_Init();		/* Need to initialize the paths of #include
605				 * directories */
606	Var_Init();		/* As well as the lists of variables for
607				 * parsing arguments */
608        str_init();
609	if (objdir != curdir)
610		Dir_AddDir(dirSearchPath, curdir);
611	Var_Set(".CURDIR", curdir, VAR_GLOBAL);
612	Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
613
614	/*
615	 * Initialize various variables.
616	 *	MAKE also gets this name, for compatibility
617	 *	.MAKEFLAGS gets set to the empty string just in case.
618	 *	MFLAGS also gets initialized empty, for compatibility.
619	 */
620	Var_Set("MAKE", argv[0], VAR_GLOBAL);
621	Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
622	Var_Set("MFLAGS", "", VAR_GLOBAL);
623	Var_Set("MACHINE", machine, VAR_GLOBAL);
624#ifdef MACHINE_ARCH
625	Var_Set("MACHINE_ARCH", MACHINE_ARCH, VAR_GLOBAL);
626#endif
627
628	/*
629	 * First snag any flags out of the MAKE environment variable.
630	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
631	 * in a different format).
632	 */
633#ifdef POSIX
634	Main_ParseArgLine(getenv("MAKEFLAGS"));
635#else
636	Main_ParseArgLine(getenv("MAKE"));
637#endif
638
639	MainParseArgs(argc, argv);
640
641	/*
642	 * Be compatible if user did not specify -j and did not explicitly
643	 * turned compatibility on
644	 */
645	if (!compatMake && !forceJobs)
646		compatMake = TRUE;
647
648	/*
649	 * Initialize archive, target and suffix modules in preparation for
650	 * parsing the makefile(s)
651	 */
652	Arch_Init();
653	Targ_Init();
654	Suff_Init();
655
656	DEFAULT = NILGNODE;
657	(void)time(&now);
658
659	/*
660	 * Set up the .TARGETS variable to contain the list of targets to be
661	 * created. If none specified, make the variable empty -- the parser
662	 * will fill the thing in with the default or .MAIN target.
663	 */
664	if (!Lst_IsEmpty(create)) {
665		LstNode ln;
666
667		for (ln = Lst_First(create); ln != NILLNODE;
668		    ln = Lst_Succ(ln)) {
669			char *name = (char *)Lst_Datum(ln);
670
671			Var_Append(".TARGETS", name, VAR_GLOBAL);
672		}
673	} else
674		Var_Set(".TARGETS", "", VAR_GLOBAL);
675
676
677	/*
678	 * If no user-supplied system path was given (through the -m option)
679	 * add the directories from the DEFSYSPATH (more than one may be given
680	 * as dir1:...:dirn) to the system include path.
681	 */
682	if (Lst_IsEmpty(sysIncPath)) {
683		for (start = syspath; *start != '\0'; start = cp) {
684			for (cp = start; *cp != '\0' && *cp != ':'; cp++)
685				continue;
686			if (*cp == '\0') {
687				Dir_AddDir(sysIncPath, start);
688			} else {
689				*cp++ = '\0';
690				Dir_AddDir(sysIncPath, start);
691			}
692		}
693	}
694
695	/*
696	 * Read in the built-in rules first, followed by the specified
697	 * makefile, if it was (makefile != (char *) NULL), or the default
698	 * Makefile and makefile, in that order, if it wasn't.
699	 */
700	if (!noBuiltins) {
701		LstNode ln;
702
703		sysMkPath = Lst_Init (FALSE);
704		Dir_Expand (_PATH_DEFSYSMK, sysIncPath, sysMkPath);
705		if (Lst_IsEmpty(sysMkPath))
706			Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
707		ln = Lst_Find(sysMkPath, (ClientData)NULL, ReadMakefile);
708		if (ln != NILLNODE)
709			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
710	}
711
712	if (!Lst_IsEmpty(makefiles)) {
713		LstNode ln;
714
715		ln = Lst_Find(makefiles, (ClientData)NULL, ReadMakefile);
716		if (ln != NILLNODE)
717			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
718	} else if (!ReadMakefile("makefile", NULL))
719		(void)ReadMakefile("Makefile", NULL);
720
721	(void)ReadMakefile(".depend", NULL);
722
723	Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
724	if (p1)
725	    free(p1);
726
727	/* Install all the flags into the MAKE envariable. */
728	if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
729#ifdef POSIX
730		setenv("MAKEFLAGS", p, 1);
731#else
732		setenv("MAKE", p, 1);
733#endif
734	if (p1)
735	    free(p1);
736
737	/*
738	 * For compatibility, look at the directories in the VPATH variable
739	 * and add them to the search path, if the variable is defined. The
740	 * variable's value is in the same format as the PATH envariable, i.e.
741	 * <directory>:<directory>:<directory>...
742	 */
743	if (Var_Exists("VPATH", VAR_CMD)) {
744		char *vpath, *path, *cp, savec;
745		/*
746		 * GCC stores string constants in read-only memory, but
747		 * Var_Subst will want to write this thing, so store it
748		 * in an array
749		 */
750		static char VPATH[] = "${VPATH}";
751
752		vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
753		path = vpath;
754		do {
755			/* skip to end of directory */
756			for (cp = path; *cp != ':' && *cp != '\0'; cp++)
757				continue;
758			/* Save terminator character so know when to stop */
759			savec = *cp;
760			*cp = '\0';
761			/* Add directory to search path */
762			Dir_AddDir(dirSearchPath, path);
763			*cp = savec;
764			path = cp + 1;
765		} while (savec == ':');
766		(void)free((Address)vpath);
767	}
768
769	/*
770	 * Now that all search paths have been read for suffixes et al, it's
771	 * time to add the default search path to their lists...
772	 */
773	Suff_DoPaths();
774
775	/* print the initial graph, if the user requested it */
776	if (DEBUG(GRAPH1))
777		Targ_PrintGraph(1);
778
779	/* print the values of any variables requested by the user */
780	if (printVars) {
781		LstNode ln;
782
783		for (ln = Lst_First(variables); ln != NILLNODE;
784		    ln = Lst_Succ(ln)) {
785			char *value = Var_Subst(NULL, (char *)Lst_Datum(ln),
786					  VAR_GLOBAL, FALSE);
787
788			printf("%s\n", value ? value : "");
789		}
790	}
791
792	/*
793	 * Have now read the entire graph and need to make a list of targets
794	 * to create. If none was given on the command line, we consult the
795	 * parsing module to find the main target(s) to create.
796	 */
797	if (Lst_IsEmpty(create))
798		targs = Parse_MainName();
799	else
800		targs = Targ_FindList(create, TARG_CREATE);
801
802	if (!compatMake && !printVars) {
803		/*
804		 * Initialize job module before traversing the graph, now that
805		 * any .BEGIN and .END targets have been read.  This is done
806		 * only if the -q flag wasn't given (to prevent the .BEGIN from
807		 * being executed should it exist).
808		 */
809		if (!queryFlag) {
810			if (maxLocal == -1)
811				maxLocal = maxJobs;
812			Job_Init(maxJobs, maxLocal);
813			jobsRunning = TRUE;
814		}
815
816		/* Traverse the graph, checking on all the targets */
817		outOfDate = Make_Run(targs);
818	} else if (!printVars) {
819		/*
820		 * Compat_Init will take care of creating all the targets as
821		 * well as initializing the module.
822		 */
823		Compat_Run(targs);
824	}
825
826	Lst_Destroy(targs, NOFREE);
827	Lst_Destroy(variables, NOFREE);
828	Lst_Destroy(makefiles, NOFREE);
829	Lst_Destroy(create, (void (*) __P((ClientData))) free);
830
831	/* print the graph now it's been processed if the user requested it */
832	if (DEBUG(GRAPH2))
833		Targ_PrintGraph(2);
834
835	Suff_End();
836        Targ_End();
837	Arch_End();
838	str_end();
839	Var_End();
840	Parse_End();
841	Dir_End();
842
843	if (queryFlag && outOfDate)
844		return(1);
845	else
846		return(0);
847}
848
849/*-
850 * ReadMakefile  --
851 *	Open and parse the given makefile.
852 *
853 * Results:
854 *	TRUE if ok. FALSE if couldn't open file.
855 *
856 * Side Effects:
857 *	lots
858 */
859static Boolean
860ReadMakefile(p, q)
861	ClientData p, q;
862{
863	char *fname = p;		/* makefile to read */
864	extern Lst parseIncPath;
865	FILE *stream;
866	char *name, path[MAXPATHLEN + 1];
867
868	if (!strcmp(fname, "-")) {
869		Parse_File("(stdin)", stdin);
870		Var_Set("MAKEFILE", "", VAR_GLOBAL);
871	} else {
872		/* if we've chdir'd, rebuild the path name */
873		if (curdir != objdir && *fname != '/') {
874			(void)sprintf(path, "%s/%s", curdir, fname);
875			if ((stream = fopen(path, "r")) != NULL) {
876				fname = path;
877				goto found;
878			}
879		} else if ((stream = fopen(fname, "r")) != NULL)
880			goto found;
881		/* look in -I and system include directories. */
882		name = Dir_FindFile(fname, parseIncPath);
883		if (!name)
884			name = Dir_FindFile(fname, sysIncPath);
885		if (!name || !(stream = fopen(name, "r")))
886			return(FALSE);
887		fname = name;
888		/*
889		 * set the MAKEFILE variable desired by System V fans -- the
890		 * placement of the setting here means it gets set to the last
891		 * makefile specified, as it is set by SysV make.
892		 */
893found:		Var_Set("MAKEFILE", fname, VAR_GLOBAL);
894		Parse_File(fname, stream);
895		(void)fclose(stream);
896	}
897	return(TRUE);
898}
899
900/*-
901 * Cmd_Exec --
902 *	Execute the command in cmd, and return the output of that command
903 *	in a string.
904 *
905 * Results:
906 *	A string containing the output of the command, or the empty string
907 *	If err is not NULL, it contains the reason for the command failure
908 *
909 * Side Effects:
910 *	The string must be freed by the caller.
911 */
912char *
913Cmd_Exec(cmd, err)
914    char *cmd;
915    char **err;
916{
917    char	*args[4];   	/* Args for invoking the shell */
918    int 	fds[2];	    	/* Pipe streams */
919    int 	cpid;	    	/* Child PID */
920    int 	pid;	    	/* PID from wait() */
921    char	*res;		/* result */
922    int		status;		/* command exit status */
923    Buffer	buf;		/* buffer to store the result */
924    char	*cp;
925    int		cc;
926
927
928    *err = NULL;
929
930    /*
931     * Set up arguments for shell
932     */
933    args[0] = "sh";
934    args[1] = "-c";
935    args[2] = cmd;
936    args[3] = NULL;
937
938    /*
939     * Open a pipe for fetching its output
940     */
941    if (pipe(fds) == -1) {
942	*err = "Couldn't create pipe for \"%s\"";
943	goto bad;
944    }
945
946    /*
947     * Fork
948     */
949    switch (cpid = vfork()) {
950    case 0:
951	/*
952	 * Close input side of pipe
953	 */
954	(void) close(fds[0]);
955
956	/*
957	 * Duplicate the output stream to the shell's output, then
958	 * shut the extra thing down. Note we don't fetch the error
959	 * stream...why not? Why?
960	 */
961	(void) dup2(fds[1], 1);
962	(void) close(fds[1]);
963
964	(void) execv("/bin/sh", args);
965	_exit(1);
966	/*NOTREACHED*/
967
968    case -1:
969	*err = "Couldn't exec \"%s\"";
970	goto bad;
971
972    default:
973	/*
974	 * No need for the writing half
975	 */
976	(void) close(fds[1]);
977
978	buf = Buf_Init (MAKE_BSIZE);
979
980	do {
981	    char   result[BUFSIZ];
982	    cc = read(fds[0], result, sizeof(result));
983	    if (cc > 0)
984		Buf_AddBytes(buf, cc, (Byte *) result);
985	}
986	while (cc > 0 || (cc == -1 && errno == EINTR));
987
988	/*
989	 * Close the input side of the pipe.
990	 */
991	(void) close(fds[0]);
992
993	/*
994	 * Wait for the process to exit.
995	 */
996	while(((pid = wait(&status)) != cpid) && (pid >= 0))
997	    continue;
998
999	if (cc == -1)
1000	    *err = "Error reading shell's output for \"%s\"";
1001
1002	res = (char *)Buf_GetAll (buf, &cc);
1003	Buf_Destroy (buf, FALSE);
1004
1005	if (status)
1006	    *err = "\"%s\" returned non-zero status";
1007
1008	/*
1009	 * Null-terminate the result, convert newlines to spaces and
1010	 * install it in the variable.
1011	 */
1012	res[cc] = '\0';
1013	cp = &res[cc] - 1;
1014
1015	if (*cp == '\n') {
1016	    /*
1017	     * A final newline is just stripped
1018	     */
1019	    *cp-- = '\0';
1020	}
1021	while (cp >= res) {
1022	    if (*cp == '\n') {
1023		*cp = ' ';
1024	    }
1025	    cp--;
1026	}
1027	break;
1028    }
1029    return res;
1030bad:
1031    res = emalloc(1);
1032    *res = '\0';
1033    return res;
1034}
1035
1036/*-
1037 * Error --
1038 *	Print an error message given its format.
1039 *
1040 * Results:
1041 *	None.
1042 *
1043 * Side Effects:
1044 *	The message is printed.
1045 */
1046/* VARARGS */
1047void
1048#if __STDC__
1049Error(char *fmt, ...)
1050#else
1051Error(va_alist)
1052	va_dcl
1053#endif
1054{
1055	va_list ap;
1056#if __STDC__
1057	va_start(ap, fmt);
1058#else
1059	char *fmt;
1060
1061	va_start(ap);
1062	fmt = va_arg(ap, char *);
1063#endif
1064	(void)vfprintf(stderr, fmt, ap);
1065	va_end(ap);
1066	(void)fprintf(stderr, "\n");
1067	(void)fflush(stderr);
1068}
1069
1070/*-
1071 * Fatal --
1072 *	Produce a Fatal error message. If jobs are running, waits for them
1073 *	to finish.
1074 *
1075 * Results:
1076 *	None
1077 *
1078 * Side Effects:
1079 *	The program exits
1080 */
1081/* VARARGS */
1082void
1083#if __STDC__
1084Fatal(char *fmt, ...)
1085#else
1086Fatal(va_alist)
1087	va_dcl
1088#endif
1089{
1090	va_list ap;
1091#if __STDC__
1092	va_start(ap, fmt);
1093#else
1094	char *fmt;
1095
1096	va_start(ap);
1097	fmt = va_arg(ap, char *);
1098#endif
1099	if (jobsRunning)
1100		Job_Wait();
1101
1102	(void)vfprintf(stderr, fmt, ap);
1103	va_end(ap);
1104	(void)fprintf(stderr, "\n");
1105	(void)fflush(stderr);
1106
1107	if (DEBUG(GRAPH2))
1108		Targ_PrintGraph(2);
1109	exit(2);		/* Not 1 so -q can distinguish error */
1110}
1111
1112/*
1113 * Punt --
1114 *	Major exception once jobs are being created. Kills all jobs, prints
1115 *	a message and exits.
1116 *
1117 * Results:
1118 *	None
1119 *
1120 * Side Effects:
1121 *	All children are killed indiscriminately and the program Lib_Exits
1122 */
1123/* VARARGS */
1124void
1125#if __STDC__
1126Punt(char *fmt, ...)
1127#else
1128Punt(va_alist)
1129	va_dcl
1130#endif
1131{
1132	va_list ap;
1133#if __STDC__
1134	va_start(ap, fmt);
1135#else
1136	char *fmt;
1137
1138	va_start(ap);
1139	fmt = va_arg(ap, char *);
1140#endif
1141
1142	(void)fprintf(stderr, "make: ");
1143	(void)vfprintf(stderr, fmt, ap);
1144	va_end(ap);
1145	(void)fprintf(stderr, "\n");
1146	(void)fflush(stderr);
1147
1148	DieHorribly();
1149}
1150
1151/*-
1152 * DieHorribly --
1153 *	Exit without giving a message.
1154 *
1155 * Results:
1156 *	None
1157 *
1158 * Side Effects:
1159 *	A big one...
1160 */
1161void
1162DieHorribly()
1163{
1164	if (jobsRunning)
1165		Job_AbortAll();
1166	if (DEBUG(GRAPH2))
1167		Targ_PrintGraph(2);
1168	exit(2);		/* Not 1, so -q can distinguish error */
1169}
1170
1171/*
1172 * Finish --
1173 *	Called when aborting due to errors in child shell to signal
1174 *	abnormal exit.
1175 *
1176 * Results:
1177 *	None
1178 *
1179 * Side Effects:
1180 *	The program exits
1181 */
1182void
1183Finish(errors)
1184	int errors;	/* number of errors encountered in Make_Make */
1185{
1186	Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1187}
1188
1189/*
1190 * emalloc --
1191 *	malloc, but die on error.
1192 */
1193void *
1194emalloc(len)
1195	size_t len;
1196{
1197	void *p;
1198
1199	if ((p = malloc(len)) == NULL)
1200		enomem();
1201	return(p);
1202}
1203
1204/*
1205 * estrdup --
1206 *	strdup, but die on error.
1207 */
1208char *
1209estrdup(str)
1210	const char *str;
1211{
1212	char *p;
1213
1214	if ((p = strdup(str)) == NULL)
1215		enomem();
1216	return(p);
1217}
1218
1219/*
1220 * erealloc --
1221 *	realloc, but die on error.
1222 */
1223void *
1224erealloc(ptr, size)
1225	void *ptr;
1226	size_t size;
1227{
1228	if ((ptr = realloc(ptr, size)) == NULL)
1229		enomem();
1230	return(ptr);
1231}
1232
1233/*
1234 * enomem --
1235 *	die when out of memory.
1236 */
1237void
1238enomem()
1239{
1240	err(2, NULL);
1241}
1242
1243/*
1244 * enunlink --
1245 *	Remove a file carefully, avoiding directories.
1246 */
1247int
1248eunlink(file)
1249	const char *file;
1250{
1251	struct stat st;
1252
1253	if (lstat(file, &st) == -1)
1254		return -1;
1255
1256	if (S_ISDIR(st.st_mode)) {
1257		errno = EISDIR;
1258		return -1;
1259	}
1260	return unlink(file);
1261}
1262
1263/*
1264 * usage --
1265 *	exit with usage message
1266 */
1267static void
1268usage()
1269{
1270	(void)fprintf(stderr, "%s\n%s\n%s\n",
1271"usage: make [-Beiknqrst] [-D variable] [-d flags] [-f makefile ]",
1272"            [-I directory] [-j max_jobs] [-m directory] [-V variable]",
1273"            [variable=value] [target ...]");
1274	exit(2);
1275}
1276
1277
1278int
1279PrintAddr(a, b)
1280    ClientData a;
1281    ClientData b;
1282{
1283    printf("%lx ", (unsigned long) a);
1284    return b ? 0 : 0;
1285}
1286