main.c revision 98138
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#if 0
43static char copyright[] =
44"@(#) Copyright (c) 1988, 1989, 1990, 1993\n\
45	The Regents of the University of California.  All rights reserved.\n";
46#endif
47#endif /* not lint */
48#include <sys/cdefs.h>
49__FBSDID("$FreeBSD: head/usr.bin/make/main.c 98138 2002-06-12 04:18:31Z jmallett $");
50
51/*-
52 * main.c --
53 *	The main file for this entire program. Exit routines etc
54 *	reside here.
55 *
56 * Utility functions defined in this file:
57 *	Main_ParseArgLine	Takes a line of arguments, breaks them and
58 *				treats them as if they were given when first
59 *				invoked. Used by the parse module to implement
60 *				the .MFLAGS target.
61 *
62 *	Error			Print a tagged error message. The global
63 *				MAKE variable must have been defined. This
64 *				takes a format string and two optional
65 *				arguments for it.
66 *
67 *	Fatal			Print an error message and exit. Also takes
68 *				a format string and two arguments.
69 *
70 *	Punt			Aborts all jobs and exits with a message. Also
71 *				takes a format string and two arguments.
72 *
73 *	Finish			Finish things up by printing the number of
74 *				errors which occured, as passed to it, and
75 *				exiting.
76 */
77
78#include <sys/types.h>
79#include <sys/time.h>
80#include <sys/param.h>
81#include <sys/resource.h>
82#include <sys/signal.h>
83#include <sys/stat.h>
84#if defined(__i386__)
85#include <sys/sysctl.h>
86#endif
87#ifndef MACHINE
88#include <sys/utsname.h>
89#endif
90#include <sys/wait.h>
91#include <err.h>
92#include <stdlib.h>
93#include <errno.h>
94#include <fcntl.h>
95#include <stdio.h>
96#include <sysexits.h>
97#include <stdarg.h>
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(int, char **);
140char *			chdir_verify_path(char *, char *);
141static int		ReadMakefile(void *, void *);
142static void		usage(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, (void *)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 = emalloc(strlen(optarg) + 1);
281			(void)strcpy(p, optarg);
282			(void)Lst_AtEnd(envFirstVars, (void *)p);
283			Var_Append(MAKEFLAGS, "-E", VAR_GLOBAL);
284			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
285			break;
286		case 'e':
287			checkEnvFirst = TRUE;
288			Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
289			break;
290		case 'f':
291			(void)Lst_AtEnd(makefiles, (void *)optarg);
292			break;
293		case 'i':
294			ignoreErrors = TRUE;
295			Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
296			break;
297		case 'j': {
298			char *endptr;
299
300			forceJobs = TRUE;
301			maxJobs = strtol(optarg, &endptr, 10);
302			if (maxJobs <= 0 || *endptr != '\0') {
303				warnx("illegal number, -j argument -- %s",
304				    optarg);
305				usage();
306			}
307#ifndef REMOTE
308			maxLocal = maxJobs;
309#endif
310			Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
311			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
312			break;
313		}
314		case 'k':
315			keepgoing = TRUE;
316			Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
317			break;
318		case 'm':
319			Dir_AddDir(sysIncPath, optarg);
320			Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
321			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
322			break;
323		case 'n':
324			noExecute = TRUE;
325			Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
326			break;
327		case 'q':
328			queryFlag = TRUE;
329			/* Kind of nonsensical, wot? */
330			Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
331			break;
332		case 'r':
333			noBuiltins = TRUE;
334			Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
335			break;
336		case 's':
337			beSilent = TRUE;
338			Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
339			break;
340		case 't':
341			touchFlag = TRUE;
342			Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
343			break;
344		case 'v':
345			beVerbose = TRUE;
346			Var_Append(MAKEFLAGS, "-v", VAR_GLOBAL);
347			break;
348		default:
349		case '?':
350			usage();
351		}
352	}
353
354	oldVars = TRUE;
355
356	/*
357	 * See if the rest of the arguments are variable assignments and
358	 * perform them if so. Else take them to be targets and stuff them
359	 * on the end of the "create" list.
360	 */
361	for (argv += optind, argc -= optind; *argv; ++argv, --argc)
362		if (Parse_IsVar(*argv))
363			Parse_DoVar(*argv, VAR_CMD);
364		else {
365			if (!**argv)
366				Punt("illegal (null) argument.");
367			if (**argv == '-') {
368				if ((*argv)[1])
369					optind = 0;     /* -flag... */
370				else
371					optind = 1;     /* - */
372				goto rearg;
373			}
374			(void)Lst_AtEnd(create, (void *)estrdup(*argv));
375		}
376}
377
378/*-
379 * Main_ParseArgLine --
380 *  	Used by the parse module when a .MFLAGS or .MAKEFLAGS target
381 *	is encountered and by main() when reading the .MAKEFLAGS envariable.
382 *	Takes a line of arguments and breaks it into its
383 * 	component words and passes those words and the number of them to the
384 *	MainParseArgs function.
385 *	The line should have all its leading whitespace removed.
386 *
387 * Results:
388 *	None
389 *
390 * Side Effects:
391 *	Only those that come from the various arguments.
392 */
393void
394Main_ParseArgLine(line)
395	char *line;			/* Line to fracture */
396{
397	char **argv;			/* Manufactured argument vector */
398	int argc;			/* Number of arguments in argv */
399
400	if (line == NULL)
401		return;
402	for (; *line == ' '; ++line)
403		continue;
404	if (!*line)
405		return;
406
407	argv = brk_string(line, &argc, TRUE);
408	MainParseArgs(argc, argv);
409}
410
411char *
412chdir_verify_path(path, obpath)
413	char *path;
414	char *obpath;
415{
416	struct stat sb;
417
418	if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
419		if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) {
420			warn("warning: %s", path);
421			return 0;
422		}
423		return obpath;
424	}
425
426	return 0;
427}
428
429
430/*-
431 * main --
432 *	The main function, for obvious reasons. Initializes variables
433 *	and a few modules, then parses the arguments give it in the
434 *	environment and on the command line. Reads the system makefile
435 *	followed by either Makefile, makefile or the file given by the
436 *	-f argument. Sets the .MAKEFLAGS PMake variable based on all the
437 *	flags it has received by then uses either the Make or the Compat
438 *	module to create the initial list of targets.
439 *
440 * Results:
441 *	If -q was given, exits -1 if anything was out-of-date. Else it exits
442 *	0.
443 *
444 * Side Effects:
445 *	The program exits when done. Targets are created. etc. etc. etc.
446 */
447int
448main(argc, argv)
449	int argc;
450	char **argv;
451{
452	Lst targs;	/* target nodes to create -- passed to Make_Init */
453	Boolean outOfDate = TRUE; 	/* FALSE if all targets up to date */
454	struct stat sa;
455	char *p, *p1, *path, *pathp;
456	char mdpath[MAXPATHLEN];
457	char obpath[MAXPATHLEN];
458	char cdpath[MAXPATHLEN];
459    	char *machine = getenv("MACHINE");
460	char *machine_arch = getenv("MACHINE_ARCH");
461	char *machine_cpu = getenv("MACHINE_CPU");
462	Lst sysMkPath;			/* Path of sys.mk */
463	char *cp = NULL, *start;
464					/* avoid faults on read-only strings */
465	static char syspath[] = _PATH_DEFSYSPATH;
466
467#if DEFSHELL == 2
468	/*
469	 * Turn off ENV to make ksh happier.
470	 */
471	unsetenv("ENV");
472#endif
473
474#ifdef RLIMIT_NOFILE
475	/*
476	 * get rid of resource limit on file descriptors
477	 */
478	{
479		struct rlimit rl;
480		if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
481		    rl.rlim_cur != rl.rlim_max) {
482			rl.rlim_cur = rl.rlim_max;
483			(void) setrlimit(RLIMIT_NOFILE, &rl);
484		}
485	}
486#endif
487	/*
488	 * Find where we are...
489	 * All this code is so that we know where we are when we start up
490	 * on a different machine with pmake.
491	 */
492	curdir = cdpath;
493	if (getcwd(curdir, MAXPATHLEN) == NULL)
494		err(2, NULL);
495
496	if (stat(curdir, &sa) == -1)
497	    err(2, "%s", curdir);
498
499#if defined(__i386__) && defined(__FreeBSD_version) && \
500    __FreeBSD_version > 300003
501	/*
502	 * PC-98 kernel sets the `i386' string to the utsname.machine and
503	 * it cannot be distinguished from IBM-PC by uname(3).  Therefore,
504	 * we check machine.ispc98 and adjust the machine variable before
505	 * using usname(3) below.
506	 * NOTE: machdep.ispc98 was defined on 1998/8/31. At that time,
507	 * __FreeBSD_version was defined as 300003. So, this check can
508	 * safely be done with any kernel with version > 300003.
509	 */
510	if (!machine) {
511		int	ispc98;
512		size_t	len;
513
514		len = sizeof(ispc98);
515		if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
516			if (ispc98)
517				machine = "pc98";
518		}
519	}
520#endif
521
522	/*
523	 * Get the name of this type of MACHINE from utsname
524	 * so we can share an executable for similar machines.
525	 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
526	 *
527	 * Note that while MACHINE is decided at run-time,
528	 * MACHINE_ARCH is always known at compile time.
529	 */
530	if (!machine) {
531#ifndef MACHINE
532	    struct utsname utsname;
533
534	    if (uname(&utsname) == -1)
535		    err(2, "uname");
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#ifdef MAKE_VERSION
663	Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
664#endif
665
666	/*
667	 * First snag any flags out of the MAKE environment variable.
668	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
669	 * in a different format).
670	 */
671#ifdef POSIX
672	Main_ParseArgLine(getenv("MAKEFLAGS"));
673#else
674	Main_ParseArgLine(getenv("MAKE"));
675#endif
676
677	MainParseArgs(argc, argv);
678
679	/*
680	 * Be compatible if user did not specify -j and did not explicitly
681	 * turned compatibility on
682	 */
683	if (!compatMake && !forceJobs)
684		compatMake = TRUE;
685
686	/*
687	 * Initialize archive, target and suffix modules in preparation for
688	 * parsing the makefile(s)
689	 */
690	Arch_Init();
691	Targ_Init();
692	Suff_Init();
693
694	DEFAULT = NULL;
695	(void)time(&now);
696
697	/*
698	 * Set up the .TARGETS variable to contain the list of targets to be
699	 * created. If none specified, make the variable empty -- the parser
700	 * will fill the thing in with the default or .MAIN target.
701	 */
702	if (!Lst_IsEmpty(create)) {
703		LstNode ln;
704
705		for (ln = Lst_First(create); ln != NULL;
706		    ln = Lst_Succ(ln)) {
707			char *name = (char *)Lst_Datum(ln);
708
709			Var_Append(".TARGETS", name, VAR_GLOBAL);
710		}
711	} else
712		Var_Set(".TARGETS", "", VAR_GLOBAL);
713
714
715	/*
716	 * If no user-supplied system path was given (through the -m option)
717	 * add the directories from the DEFSYSPATH (more than one may be given
718	 * as dir1:...:dirn) to the system include path.
719	 */
720	if (Lst_IsEmpty(sysIncPath)) {
721		for (start = syspath; *start != '\0'; start = cp) {
722			for (cp = start; *cp != '\0' && *cp != ':'; cp++)
723				continue;
724			if (*cp == '\0') {
725				Dir_AddDir(sysIncPath, start);
726			} else {
727				*cp++ = '\0';
728				Dir_AddDir(sysIncPath, start);
729			}
730		}
731	}
732
733	/*
734	 * Read in the built-in rules first, followed by the specified
735	 * makefile, if it was (makefile != (char *) NULL), or the default
736	 * Makefile and makefile, in that order, if it wasn't.
737	 */
738	if (!noBuiltins) {
739		LstNode ln;
740
741		sysMkPath = Lst_Init (FALSE);
742		Dir_Expand (_PATH_DEFSYSMK, sysIncPath, sysMkPath);
743		if (Lst_IsEmpty(sysMkPath))
744			Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
745		ln = Lst_Find(sysMkPath, (void *)NULL, ReadMakefile);
746		if (ln != NULL)
747			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
748	}
749
750	if (!Lst_IsEmpty(makefiles)) {
751		LstNode ln;
752
753		ln = Lst_Find(makefiles, (void *)NULL, ReadMakefile);
754		if (ln != NULL)
755			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
756	} else if (!ReadMakefile("BSDmakefile", NULL))
757	    if (!ReadMakefile("makefile", NULL))
758		(void)ReadMakefile("Makefile", NULL);
759
760	(void)ReadMakefile(".depend", NULL);
761
762	Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
763	efree(p1);
764
765	/* Install all the flags into the MAKE envariable. */
766	if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
767#ifdef POSIX
768		setenv("MAKEFLAGS", p, 1);
769#else
770		setenv("MAKE", p, 1);
771#endif
772	efree(p1);
773
774	/*
775	 * For compatibility, look at the directories in the VPATH variable
776	 * and add them to the search path, if the variable is defined. The
777	 * variable's value is in the same format as the PATH envariable, i.e.
778	 * <directory>:<directory>:<directory>...
779	 */
780	if (Var_Exists("VPATH", VAR_CMD)) {
781		char *vpath, *path, *cp, savec;
782		/*
783		 * GCC stores string constants in read-only memory, but
784		 * Var_Subst will want to write this thing, so store it
785		 * in an array
786		 */
787		static char VPATH[] = "${VPATH}";
788
789		vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
790		path = vpath;
791		do {
792			/* skip to end of directory */
793			for (cp = path; *cp != ':' && *cp != '\0'; cp++)
794				continue;
795			/* Save terminator character so know when to stop */
796			savec = *cp;
797			*cp = '\0';
798			/* Add directory to search path */
799			Dir_AddDir(dirSearchPath, path);
800			*cp = savec;
801			path = cp + 1;
802		} while (savec == ':');
803		(void)free(vpath);
804	}
805
806	/*
807	 * Now that all search paths have been read for suffixes et al, it's
808	 * time to add the default search path to their lists...
809	 */
810	Suff_DoPaths();
811
812	/* print the initial graph, if the user requested it */
813	if (DEBUG(GRAPH1))
814		Targ_PrintGraph(1);
815
816	/* print the values of any variables requested by the user */
817	if (printVars) {
818		LstNode ln;
819
820		for (ln = Lst_First(variables); ln != NULL;
821		    ln = Lst_Succ(ln)) {
822			char *value;
823			if (expandVars) {
824				p1 = emalloc(strlen((char *)Lst_Datum(ln)) + 1 + 3);
825				/* This sprintf is safe, because of the malloc above */
826				(void)sprintf(p1, "${%s}", (char *)Lst_Datum(ln));
827				value = Var_Subst(NULL, p1, VAR_GLOBAL, FALSE);
828			} else {
829				value = Var_Value((char *)Lst_Datum(ln),
830						  VAR_GLOBAL, &p1);
831			}
832			printf("%s\n", value ? value : "");
833			if (p1)
834				free(p1);
835		}
836	}
837
838	/*
839	 * Have now read the entire graph and need to make a list of targets
840	 * to create. If none was given on the command line, we consult the
841	 * parsing module to find the main target(s) to create.
842	 */
843	if (Lst_IsEmpty(create))
844		targs = Parse_MainName();
845	else
846		targs = Targ_FindList(create, TARG_CREATE);
847
848	if (!compatMake && !printVars) {
849		/*
850		 * Initialize job module before traversing the graph, now that
851		 * any .BEGIN and .END targets have been read.  This is done
852		 * only if the -q flag wasn't given (to prevent the .BEGIN from
853		 * being executed should it exist).
854		 */
855		if (!queryFlag) {
856			if (maxLocal == -1)
857				maxLocal = maxJobs;
858			Job_Init(maxJobs, maxLocal);
859			jobsRunning = TRUE;
860		}
861
862		/* Traverse the graph, checking on all the targets */
863		outOfDate = Make_Run(targs);
864	} else if (!printVars) {
865		/*
866		 * Compat_Init will take care of creating all the targets as
867		 * well as initializing the module.
868		 */
869		Compat_Run(targs);
870	}
871
872	Lst_Destroy(targs, NOFREE);
873	Lst_Destroy(variables, NOFREE);
874	Lst_Destroy(makefiles, NOFREE);
875	Lst_Destroy(create, (void (*)(void *)) free);
876
877	/* print the graph now it's been processed if the user requested it */
878	if (DEBUG(GRAPH2))
879		Targ_PrintGraph(2);
880
881	Suff_End();
882        Targ_End();
883	Arch_End();
884	str_end();
885	Var_End();
886	Parse_End();
887	Dir_End();
888
889	if (queryFlag && outOfDate)
890		return(1);
891	else
892		return(0);
893}
894
895/*-
896 * ReadMakefile  --
897 *	Open and parse the given makefile.
898 *
899 * Results:
900 *	TRUE if ok. FALSE if couldn't open file.
901 *
902 * Side Effects:
903 *	lots
904 */
905static Boolean
906ReadMakefile(p, q)
907	void *p;
908	void *q __unused;
909{
910	char *fname = p;		/* makefile to read */
911	extern Lst parseIncPath;
912	FILE *stream;
913	char *name, path[MAXPATHLEN];
914	char *MAKEFILE;
915	int setMAKEFILE;
916
917	if (!strcmp(fname, "-")) {
918		Parse_File("(stdin)", stdin);
919		Var_Set("MAKEFILE", "", VAR_GLOBAL);
920	} else {
921		setMAKEFILE = strcmp(fname, ".depend");
922
923		/* if we've chdir'd, rebuild the path name */
924		if (curdir != objdir && *fname != '/') {
925			(void)snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
926			if (realpath(path, path) != NULL &&
927			    (stream = fopen(path, "r")) != NULL) {
928				MAKEFILE = fname;
929				fname = path;
930				goto found;
931			}
932		} else if (realpath(fname, path) != NULL) {
933			MAKEFILE = fname;
934			fname = path;
935			if ((stream = fopen(fname, "r")) != NULL)
936				goto found;
937		}
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		MAKEFILE = 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:
951		if (setMAKEFILE)
952			Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
953		Parse_File(fname, stream);
954		(void)fclose(stream);
955	}
956	return(TRUE);
957}
958
959/*-
960 * Cmd_Exec --
961 *	Execute the command in cmd, and return the output of that command
962 *	in a string.
963 *
964 * Results:
965 *	A string containing the output of the command, or the empty string
966 *	If err is not NULL, it contains the reason for the command failure
967 *
968 * Side Effects:
969 *	The string must be freed by the caller.
970 */
971char *
972Cmd_Exec(cmd, err)
973    char *cmd;
974    char **err;
975{
976    char	*args[4];   	/* Args for invoking the shell */
977    int 	fds[2];	    	/* Pipe streams */
978    int 	cpid;	    	/* Child PID */
979    int 	pid;	    	/* PID from wait() */
980    char	*res;		/* result */
981    int		status;		/* command exit status */
982    Buffer	buf;		/* buffer to store the result */
983    char	*cp;
984    int		cc;
985
986
987    *err = NULL;
988
989    /*
990     * Set up arguments for shell
991     */
992    args[0] = "sh";
993    args[1] = "-c";
994    args[2] = cmd;
995    args[3] = NULL;
996
997    /*
998     * Open a pipe for fetching its output
999     */
1000    if (pipe(fds) == -1) {
1001	*err = "Couldn't create pipe for \"%s\"";
1002	goto bad;
1003    }
1004
1005    /*
1006     * Fork
1007     */
1008    switch (cpid = vfork()) {
1009    case 0:
1010	/*
1011	 * Close input side of pipe
1012	 */
1013	(void) close(fds[0]);
1014
1015	/*
1016	 * Duplicate the output stream to the shell's output, then
1017	 * shut the extra thing down. Note we don't fetch the error
1018	 * stream...why not? Why?
1019	 */
1020	(void) dup2(fds[1], 1);
1021	(void) close(fds[1]);
1022
1023#if DEFSHELL == 1
1024	(void) execv("/bin/sh", args);
1025#elif DEFSHELL == 2
1026	(void) execv("/bin/ksh", args);
1027#else
1028#error "DEFSHELL must be 1 or 2."
1029#endif
1030	_exit(1);
1031	/*NOTREACHED*/
1032
1033    case -1:
1034	*err = "Couldn't exec \"%s\"";
1035	goto bad;
1036
1037    default:
1038	/*
1039	 * No need for the writing half
1040	 */
1041	(void) close(fds[1]);
1042
1043	buf = Buf_Init (MAKE_BSIZE);
1044
1045	do {
1046	    char   result[BUFSIZ];
1047	    cc = read(fds[0], result, sizeof(result));
1048	    if (cc > 0)
1049		Buf_AddBytes(buf, cc, (Byte *) result);
1050	}
1051	while (cc > 0 || (cc == -1 && errno == EINTR));
1052
1053	/*
1054	 * Close the input side of the pipe.
1055	 */
1056	(void) close(fds[0]);
1057
1058	/*
1059	 * Wait for the process to exit.
1060	 */
1061	while(((pid = wait(&status)) != cpid) && (pid >= 0))
1062	    continue;
1063
1064	if (cc == -1)
1065	    *err = "Error reading shell's output for \"%s\"";
1066
1067	res = (char *)Buf_GetAll (buf, &cc);
1068	Buf_Destroy (buf, FALSE);
1069
1070	if (status)
1071	    *err = "\"%s\" returned non-zero status";
1072
1073	/*
1074	 * Null-terminate the result, convert newlines to spaces and
1075	 * install it in the variable.
1076	 */
1077	res[cc] = '\0';
1078	cp = &res[cc] - 1;
1079
1080	if (*cp == '\n') {
1081	    /*
1082	     * A final newline is just stripped
1083	     */
1084	    *cp-- = '\0';
1085	}
1086	while (cp >= res) {
1087	    if (*cp == '\n') {
1088		*cp = ' ';
1089	    }
1090	    cp--;
1091	}
1092	break;
1093    }
1094    return res;
1095bad:
1096    res = emalloc(1);
1097    *res = '\0';
1098    return res;
1099}
1100
1101/*-
1102 * Error --
1103 *	Print an error message given its format.
1104 *
1105 * Results:
1106 *	None.
1107 *
1108 * Side Effects:
1109 *	The message is printed.
1110 */
1111/* VARARGS */
1112void
1113Error(const char *fmt, ...)
1114{
1115	va_list ap;
1116
1117	va_start(ap, fmt);
1118	(void)vfprintf(stderr, fmt, ap);
1119	va_end(ap);
1120	(void)fprintf(stderr, "\n");
1121	(void)fflush(stderr);
1122}
1123
1124/*-
1125 * Fatal --
1126 *	Produce a Fatal error message. If jobs are running, waits for them
1127 *	to finish.
1128 *
1129 * Results:
1130 *	None
1131 *
1132 * Side Effects:
1133 *	The program exits
1134 */
1135/* VARARGS */
1136void
1137Fatal(const char *fmt, ...)
1138{
1139	va_list ap;
1140
1141	va_start(ap, fmt);
1142	if (jobsRunning)
1143		Job_Wait();
1144
1145	(void)vfprintf(stderr, fmt, ap);
1146	va_end(ap);
1147	(void)fprintf(stderr, "\n");
1148	(void)fflush(stderr);
1149
1150	if (DEBUG(GRAPH2))
1151		Targ_PrintGraph(2);
1152	exit(2);		/* Not 1 so -q can distinguish error */
1153}
1154
1155/*
1156 * Punt --
1157 *	Major exception once jobs are being created. Kills all jobs, prints
1158 *	a message and exits.
1159 *
1160 * Results:
1161 *	None
1162 *
1163 * Side Effects:
1164 *	All children are killed indiscriminately and the program Lib_Exits
1165 */
1166/* VARARGS */
1167void
1168Punt(const char *fmt, ...)
1169{
1170	va_list ap;
1171
1172	va_start(ap, fmt);
1173	(void)fprintf(stderr, "make: ");
1174	(void)vfprintf(stderr, fmt, ap);
1175	va_end(ap);
1176	(void)fprintf(stderr, "\n");
1177	(void)fflush(stderr);
1178
1179	DieHorribly();
1180}
1181
1182/*-
1183 * DieHorribly --
1184 *	Exit without giving a message.
1185 *
1186 * Results:
1187 *	None
1188 *
1189 * Side Effects:
1190 *	A big one...
1191 */
1192void
1193DieHorribly()
1194{
1195	if (jobsRunning)
1196		Job_AbortAll();
1197	if (DEBUG(GRAPH2))
1198		Targ_PrintGraph(2);
1199	exit(2);		/* Not 1, so -q can distinguish error */
1200}
1201
1202/*
1203 * Finish --
1204 *	Called when aborting due to errors in child shell to signal
1205 *	abnormal exit.
1206 *
1207 * Results:
1208 *	None
1209 *
1210 * Side Effects:
1211 *	The program exits
1212 */
1213void
1214Finish(errors)
1215	int errors;	/* number of errors encountered in Make_Make */
1216{
1217	Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1218}
1219
1220/*
1221 * emalloc --
1222 *	malloc, but die on error.
1223 */
1224void *
1225emalloc(len)
1226	size_t len;
1227{
1228	void *p;
1229
1230	if ((p = malloc(len)) == NULL)
1231		enomem();
1232	return(p);
1233}
1234
1235/*
1236 * estrdup --
1237 *	strdup, but die on error.
1238 */
1239char *
1240estrdup(str)
1241	const char *str;
1242{
1243	char *p;
1244
1245	if ((p = strdup(str)) == NULL)
1246		enomem();
1247	return(p);
1248}
1249
1250/*
1251 * erealloc --
1252 *	realloc, but die on error.
1253 */
1254void *
1255erealloc(ptr, size)
1256	void *ptr;
1257	size_t size;
1258{
1259	if ((ptr = realloc(ptr, size)) == NULL)
1260		enomem();
1261	return(ptr);
1262}
1263
1264/*
1265 * enomem --
1266 *	die when out of memory.
1267 */
1268void
1269enomem()
1270{
1271	err(2, NULL);
1272}
1273
1274/*
1275 * enunlink --
1276 *	Remove a file carefully, avoiding directories.
1277 */
1278int
1279eunlink(file)
1280	const char *file;
1281{
1282	struct stat st;
1283
1284	if (lstat(file, &st) == -1)
1285		return -1;
1286
1287	if (S_ISDIR(st.st_mode)) {
1288		errno = EISDIR;
1289		return -1;
1290	}
1291	return unlink(file);
1292}
1293
1294/*
1295 * usage --
1296 *	exit with usage message
1297 */
1298static void
1299usage()
1300{
1301	(void)fprintf(stderr, "%s\n%s\n%s\n",
1302"usage: make [-Beiknqrstv] [-D variable] [-d flags] [-E variable] [-f makefile]",
1303"            [-I directory] [-j max_jobs] [-m directory] [-V variable]",
1304"            [variable=value] [target ...]");
1305	exit(2);
1306}
1307
1308
1309int
1310PrintAddr(a, b)
1311    void * a;
1312    void * b;
1313{
1314    printf("%lx ", (unsigned long) a);
1315    return b ? 0 : 0;
1316}
1317