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