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