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