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