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