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