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