main.c revision 8874
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 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
46static char sccsid[] = "@(#)main.c	8.3 (Berkeley) 3/19/94";
47#endif /* not lint */
48
49/*-
50 * main.c --
51 *	The main file for this entire program. Exit routines etc
52 *	reside here.
53 *
54 * Utility functions defined in this file:
55 *	Main_ParseArgLine	Takes a line of arguments, breaks them and
56 *				treats them as if they were given when first
57 *				invoked. Used by the parse module to implement
58 *				the .MFLAGS target.
59 *
60 *	Error			Print a tagged error message. The global
61 *				MAKE variable must have been defined. This
62 *				takes a format string and two optional
63 *				arguments for it.
64 *
65 *	Fatal			Print an error message and exit. Also takes
66 *				a format string and two arguments.
67 *
68 *	Punt			Aborts all jobs and exits with a message. Also
69 *				takes a format string and two arguments.
70 *
71 *	Finish			Finish things up by printing the number of
72 *				errors which occured, as passed to it, and
73 *				exiting.
74 */
75
76#include <sys/types.h>
77#include <sys/time.h>
78#include <sys/param.h>
79#include <sys/resource.h>
80#include <sys/signal.h>
81#include <sys/stat.h>
82#include <sys/utsname.h>
83#include <errno.h>
84#include <fcntl.h>
85#include <stdio.h>
86#if __STDC__
87#include <stdarg.h>
88#else
89#include <varargs.h>
90#endif
91#include "make.h"
92#include "hash.h"
93#include "dir.h"
94#include "job.h"
95#include "pathnames.h"
96
97#ifndef	DEFMAXLOCAL
98#define	DEFMAXLOCAL DEFMAXJOBS
99#endif	DEFMAXLOCAL
100
101#define	MAKEFLAGS	".MAKEFLAGS"
102
103Lst			create;		/* Targets to be made */
104time_t			now;		/* Time at start of make */
105GNode			*DEFAULT;	/* .DEFAULT node */
106Boolean			allPrecious;	/* .PRECIOUS given on line by itself */
107
108static Boolean		noBuiltins;	/* -r flag */
109static Lst		makefiles;	/* ordered list of makefiles to read */
110int			maxJobs;	/* -J argument */
111static int		maxLocal;	/* -L argument */
112Boolean			compatMake;	/* -B argument */
113Boolean			debug;		/* -d flag */
114Boolean			noExecute;	/* -n flag */
115Boolean			keepgoing;	/* -k flag */
116Boolean			queryFlag;	/* -q flag */
117Boolean			touchFlag;	/* -t flag */
118Boolean			usePipes;	/* !-P flag */
119Boolean			ignoreErrors;	/* -i flag */
120Boolean			beSilent;	/* -s flag */
121Boolean			oldVars;	/* variable substitution style */
122Boolean			checkEnvFirst;	/* -e flag */
123static Boolean		jobsRunning;	/* TRUE if the jobs might be running */
124
125static Boolean		ReadMakefile();
126static void		usage();
127
128static char *curdir;			/* startup directory */
129static char *objdir;			/* where we chdir'ed to */
130
131/*-
132 * MainParseArgs --
133 *	Parse a given argument vector. Called from main() and from
134 *	Main_ParseArgLine() when the .MAKEFLAGS target is used.
135 *
136 *	XXX: Deal with command line overriding .MAKEFLAGS in makefile
137 *
138 * Results:
139 *	None
140 *
141 * Side Effects:
142 *	Various global and local flags will be set depending on the flags
143 *	given
144 */
145static void
146MainParseArgs(argc, argv)
147	int argc;
148	char **argv;
149{
150	extern int optind;
151	extern char *optarg;
152	int c;
153
154	optind = 1;	/* since we're called more than once */
155#ifdef notyet
156# define OPTFLAGS "BD:I:L:PSd:ef:ij:knqrst"
157#else
158# define OPTFLAGS "D:I:d:ef:ij:knqrst"
159#endif
160rearg:	while((c = getopt(argc, argv, OPTFLAGS)) != EOF) {
161		switch(c) {
162		case 'D':
163			Var_Set(optarg, "1", VAR_GLOBAL);
164			Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
165			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
166			break;
167		case 'I':
168			Parse_AddIncludeDir(optarg);
169			Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
170			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
171			break;
172#ifdef notyet
173		case 'B':
174			compatMake = TRUE;
175			break;
176		case 'L':
177			maxLocal = atoi(optarg);
178			Var_Append(MAKEFLAGS, "-L", VAR_GLOBAL);
179			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
180			break;
181		case 'P':
182			usePipes = FALSE;
183			Var_Append(MAKEFLAGS, "-P", VAR_GLOBAL);
184			break;
185		case 'S':
186			keepgoing = FALSE;
187			Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
188			break;
189#endif
190		case 'd': {
191			char *modules = optarg;
192
193			for (; *modules; ++modules)
194				switch (*modules) {
195				case 'A':
196					debug = ~0;
197					break;
198				case 'a':
199					debug |= DEBUG_ARCH;
200					break;
201				case 'c':
202					debug |= DEBUG_COND;
203					break;
204				case 'd':
205					debug |= DEBUG_DIR;
206					break;
207				case 'f':
208					debug |= DEBUG_FOR;
209					break;
210				case 'g':
211					if (modules[1] == '1') {
212						debug |= DEBUG_GRAPH1;
213						++modules;
214					}
215					else if (modules[1] == '2') {
216						debug |= DEBUG_GRAPH2;
217						++modules;
218					}
219					break;
220				case 'j':
221					debug |= DEBUG_JOB;
222					break;
223				case 'm':
224					debug |= DEBUG_MAKE;
225					break;
226				case 's':
227					debug |= DEBUG_SUFF;
228					break;
229				case 't':
230					debug |= DEBUG_TARG;
231					break;
232				case 'v':
233					debug |= DEBUG_VAR;
234					break;
235				default:
236					(void)fprintf(stderr,
237				"make: illegal argument to d option -- %c\n",
238					    *modules);
239					usage();
240				}
241			Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
242			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
243			break;
244		}
245		case 'e':
246			checkEnvFirst = TRUE;
247			Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
248			break;
249		case 'f':
250			(void)Lst_AtEnd(makefiles, (ClientData)optarg);
251			break;
252		case 'i':
253			ignoreErrors = TRUE;
254			Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
255			break;
256		case 'j':
257			maxJobs = atoi(optarg);
258			Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
259			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
260			break;
261		case 'k':
262			keepgoing = TRUE;
263			Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
264			break;
265		case 'n':
266			noExecute = TRUE;
267			Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
268			break;
269		case 'q':
270			queryFlag = TRUE;
271			/* Kind of nonsensical, wot? */
272			Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
273			break;
274		case 'r':
275			noBuiltins = TRUE;
276			Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
277			break;
278		case 's':
279			beSilent = TRUE;
280			Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
281			break;
282		case 't':
283			touchFlag = TRUE;
284			Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
285			break;
286		default:
287		case '?':
288			usage();
289		}
290	}
291
292	oldVars = TRUE;
293
294	/*
295	 * See if the rest of the arguments are variable assignments and
296	 * perform them if so. Else take them to be targets and stuff them
297	 * on the end of the "create" list.
298	 */
299	for (argv += optind, argc -= optind; *argv; ++argv, --argc)
300		if (Parse_IsVar(*argv))
301			Parse_DoVar(*argv, VAR_CMD);
302		else {
303			if (!**argv)
304				Punt("illegal (null) argument.");
305			if (**argv == '-') {
306				if ((*argv)[1])
307					optind = 0;     /* -flag... */
308				else
309					optind = 1;     /* - */
310				goto rearg;
311			}
312			(void)Lst_AtEnd(create, (ClientData)strdup(*argv));
313		}
314}
315
316/*-
317 * Main_ParseArgLine --
318 *  	Used by the parse module when a .MFLAGS or .MAKEFLAGS target
319 *	is encountered and by main() when reading the .MAKEFLAGS envariable.
320 *	Takes a line of arguments and breaks it into its
321 * 	component words and passes those words and the number of them to the
322 *	MainParseArgs function.
323 *	The line should have all its leading whitespace removed.
324 *
325 * Results:
326 *	None
327 *
328 * Side Effects:
329 *	Only those that come from the various arguments.
330 */
331void
332Main_ParseArgLine(line)
333	char *line;			/* Line to fracture */
334{
335	char **argv;			/* Manufactured argument vector */
336	int argc;			/* Number of arguments in argv */
337
338	if (line == NULL)
339		return;
340	for (; *line == ' '; ++line)
341		continue;
342	if (!*line)
343		return;
344
345	argv = brk_string(line, &argc, TRUE);
346	MainParseArgs(argc, argv);
347}
348
349/*-
350 * main --
351 *	The main function, for obvious reasons. Initializes variables
352 *	and a few modules, then parses the arguments give it in the
353 *	environment and on the command line. Reads the system makefile
354 *	followed by either Makefile, makefile or the file given by the
355 *	-f argument. Sets the .MAKEFLAGS PMake variable based on all the
356 *	flags it has received by then uses either the Make or the Compat
357 *	module to create the initial list of targets.
358 *
359 * Results:
360 *	If -q was given, exits -1 if anything was out-of-date. Else it exits
361 *	0.
362 *
363 * Side Effects:
364 *	The program exits when done. Targets are created. etc. etc. etc.
365 */
366int
367main(argc, argv)
368	int argc;
369	char **argv;
370{
371	Lst targs;	/* target nodes to create -- passed to Make_Init */
372	Boolean outOfDate = TRUE; 	/* FALSE if all targets up to date */
373	struct stat sb, sa;
374	char *p, *p1, *path, *pwd, *getenv(), *getwd();
375	char mdpath[MAXPATHLEN + 1];
376	char obpath[MAXPATHLEN + 1];
377	char cdpath[MAXPATHLEN + 1];
378	struct utsname utsname;
379    	char *machine = getenv("MACHINE");
380
381	/*
382	 * Find where we are and take care of PWD for the automounter...
383	 * All this code is so that we know where we are when we start up
384	 * on a different machine with pmake.
385	 */
386	curdir = cdpath;
387	if (getcwd(curdir, MAXPATHLEN) == NULL) {
388		(void)fprintf(stderr, "make: %s.\n", strerror(errno));
389		exit(2);
390	}
391
392	if (stat(curdir, &sa) == -1) {
393	    (void)fprintf(stderr, "make: %s: %s.\n",
394			  curdir, strerror(errno));
395	    exit(2);
396	}
397
398	if ((pwd = getenv("PWD")) != NULL) {
399	    if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
400		sa.st_dev == sb.st_dev)
401		(void) strcpy(curdir, pwd);
402	}
403
404	/*
405	 * Get the name of this type of MACHINE from utsname
406	 * so we can share an executable for similar machines.
407	 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
408	 *
409	 * Note that while MACHINE is decided at run-time,
410	 * MACHINE_ARCH is always known at compile time.
411	 */
412    	if (!machine) {
413	    if (uname(&utsname)) {
414		    perror("make: uname");
415		    exit(2);
416	    }
417	    machine = utsname.machine;
418	}
419
420	/*
421	 * if the MAKEOBJDIR (or by default, the _PATH_OBJDIR) directory
422	 * exists, change into it and build there.  Once things are
423	 * initted, have to add the original directory to the search path,
424	 * and modify the paths for the Makefiles apropriately.  The
425	 * current directory is also placed as a variable for make scripts.
426	 */
427	if (!(path = getenv("MAKEOBJDIR"))) {
428		path = _PATH_OBJDIR;
429		(void) sprintf(mdpath, "%s.%s", path, machine);
430	}
431	else
432		(void) strncpy(mdpath, path, MAXPATHLEN + 1);
433
434	if (stat(mdpath, &sb) == 0 && S_ISDIR(sb.st_mode)) {
435
436		if (chdir(mdpath)) {
437			(void)fprintf(stderr, "make warning: %s: %s.\n",
438				      mdpath, strerror(errno));
439			objdir = curdir;
440		}
441		else {
442			if (mdpath[0] != '/') {
443				(void) sprintf(obpath, "%s/%s", curdir, mdpath);
444				objdir = obpath;
445			}
446			else
447				objdir = mdpath;
448		}
449	}
450	else {
451		if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
452
453			if (chdir(path)) {
454				(void)fprintf(stderr, "make warning: %s: %s.\n",
455					      path, strerror(errno));
456				objdir = curdir;
457			}
458			else {
459				if (path[0] != '/') {
460					(void) sprintf(obpath, "%s/%s", curdir,
461						       path);
462					objdir = obpath;
463				}
464				else
465					objdir = obpath;
466			}
467		}
468		else
469			objdir = curdir;
470	}
471
472	setenv("PWD", objdir, 1);
473
474	create = Lst_Init(FALSE);
475	makefiles = Lst_Init(FALSE);
476	beSilent = FALSE;		/* Print commands as executed */
477	ignoreErrors = FALSE;		/* Pay attention to non-zero returns */
478	noExecute = FALSE;		/* Execute all commands */
479	keepgoing = FALSE;		/* Stop on error */
480	allPrecious = FALSE;		/* Remove targets when interrupted */
481	queryFlag = FALSE;		/* This is not just a check-run */
482	noBuiltins = FALSE;		/* Read the built-in rules */
483	touchFlag = FALSE;		/* Actually update targets */
484	usePipes = TRUE;		/* Catch child output in pipes */
485	debug = 0;			/* No debug verbosity, please. */
486	jobsRunning = FALSE;
487
488	maxJobs = DEFMAXJOBS;		/* Set default max concurrency */
489	maxLocal = DEFMAXLOCAL;		/* Set default local max concurrency */
490#ifdef notyet
491	compatMake = FALSE;		/* No compat mode */
492#else
493	compatMake = TRUE;		/* No compat mode */
494#endif
495
496
497	/*
498	 * Initialize the parsing, directory and variable modules to prepare
499	 * for the reading of inclusion paths and variable settings on the
500	 * command line
501	 */
502	Dir_Init();		/* Initialize directory structures so -I flags
503				 * can be processed correctly */
504	Parse_Init();		/* Need to initialize the paths of #include
505				 * directories */
506	Var_Init();		/* As well as the lists of variables for
507				 * parsing arguments */
508        str_init();
509	if (objdir != curdir)
510		Dir_AddDir(dirSearchPath, curdir);
511	Var_Set(".CURDIR", curdir, VAR_GLOBAL);
512	Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
513
514	/*
515	 * Initialize various variables.
516	 *	MAKE also gets this name, for compatibility
517	 *	.MAKEFLAGS gets set to the empty string just in case.
518	 *	MFLAGS also gets initialized empty, for compatibility.
519	 */
520	Var_Set("MAKE", argv[0], VAR_GLOBAL);
521	Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
522	Var_Set("MFLAGS", "", VAR_GLOBAL);
523	Var_Set("MACHINE", machine, VAR_GLOBAL);
524#ifdef MACHINE_ARCH
525	Var_Set("MACHINE_ARCH", MACHINE_ARCH, VAR_GLOBAL);
526#endif
527
528	/*
529	 * First snag any flags out of the MAKE environment variable.
530	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
531	 * in a different format).
532	 */
533#ifdef POSIX
534	Main_ParseArgLine(getenv("MAKEFLAGS"));
535#else
536	Main_ParseArgLine(getenv("MAKE"));
537#endif
538
539	MainParseArgs(argc, argv);
540
541	/*
542	 * Initialize archive, target and suffix modules in preparation for
543	 * parsing the makefile(s)
544	 */
545	Arch_Init();
546	Targ_Init();
547	Suff_Init();
548
549	DEFAULT = NILGNODE;
550	(void)time(&now);
551
552	/*
553	 * Set up the .TARGETS variable to contain the list of targets to be
554	 * created. If none specified, make the variable empty -- the parser
555	 * will fill the thing in with the default or .MAIN target.
556	 */
557	if (!Lst_IsEmpty(create)) {
558		LstNode ln;
559
560		for (ln = Lst_First(create); ln != NILLNODE;
561		    ln = Lst_Succ(ln)) {
562			char *name = (char *)Lst_Datum(ln);
563
564			Var_Append(".TARGETS", name, VAR_GLOBAL);
565		}
566	} else
567		Var_Set(".TARGETS", "", VAR_GLOBAL);
568
569	/*
570	 * Read in the built-in rules first, followed by the specified makefile,
571	 * if it was (makefile != (char *) NULL), or the default Makefile and
572	 * makefile, in that order, if it wasn't.
573	 */
574	 if (!noBuiltins && !ReadMakefile(_PATH_DEFSYSMK))
575		Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
576
577	if (!Lst_IsEmpty(makefiles)) {
578		LstNode ln;
579
580		ln = Lst_Find(makefiles, (ClientData)NULL, ReadMakefile);
581		if (ln != NILLNODE)
582			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
583	} else if (!ReadMakefile("makefile"))
584		(void)ReadMakefile("Makefile");
585
586	(void)ReadMakefile(".depend");
587
588	Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
589	if (p1)
590	    free(p1);
591
592	/* Install all the flags into the MAKE envariable. */
593	if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
594#ifdef POSIX
595		setenv("MAKEFLAGS", p, 1);
596#else
597		setenv("MAKE", p, 1);
598#endif
599	if (p1)
600	    free(p1);
601
602	/*
603	 * For compatibility, look at the directories in the VPATH variable
604	 * and add them to the search path, if the variable is defined. The
605	 * variable's value is in the same format as the PATH envariable, i.e.
606	 * <directory>:<directory>:<directory>...
607	 */
608	if (Var_Exists("VPATH", VAR_CMD)) {
609		char *vpath, *path, *cp, savec;
610		/*
611		 * GCC stores string constants in read-only memory, but
612		 * Var_Subst will want to write this thing, so store it
613		 * in an array
614		 */
615		static char VPATH[] = "${VPATH}";
616
617		vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
618		path = vpath;
619		do {
620			/* skip to end of directory */
621			for (cp = path; *cp != ':' && *cp != '\0'; cp++)
622				continue;
623			/* Save terminator character so know when to stop */
624			savec = *cp;
625			*cp = '\0';
626			/* Add directory to search path */
627			Dir_AddDir(dirSearchPath, path);
628			*cp = savec;
629			path = cp + 1;
630		} while (savec == ':');
631		(void)free((Address)vpath);
632	}
633
634	/*
635	 * Now that all search paths have been read for suffixes et al, it's
636	 * time to add the default search path to their lists...
637	 */
638	Suff_DoPaths();
639
640	/* print the initial graph, if the user requested it */
641	if (DEBUG(GRAPH1))
642		Targ_PrintGraph(1);
643
644	/*
645	 * Have now read the entire graph and need to make a list of targets
646	 * to create. If none was given on the command line, we consult the
647	 * parsing module to find the main target(s) to create.
648	 */
649	if (Lst_IsEmpty(create))
650		targs = Parse_MainName();
651	else
652		targs = Targ_FindList(create, TARG_CREATE);
653
654/*
655 * this was original amMake -- want to allow parallelism, so put this
656 * back in, eventually.
657 */
658	if (!compatMake) {
659		/*
660		 * Initialize job module before traversing the graph, now that
661		 * any .BEGIN and .END targets have been read.  This is done
662		 * only if the -q flag wasn't given (to prevent the .BEGIN from
663		 * being executed should it exist).
664		 */
665		if (!queryFlag) {
666			if (maxLocal == -1)
667				maxLocal = maxJobs;
668			Job_Init(maxJobs, maxLocal);
669			jobsRunning = TRUE;
670		}
671
672		/* Traverse the graph, checking on all the targets */
673		outOfDate = Make_Run(targs);
674	} else
675		/*
676		 * Compat_Init will take care of creating all the targets as
677		 * well as initializing the module.
678		 */
679		Compat_Run(targs);
680
681	Lst_Destroy(targs, NOFREE);
682	Lst_Destroy(makefiles, NOFREE);
683	Lst_Destroy(create, (void (*) __P((ClientData))) free);
684
685	/* print the graph now it's been processed if the user requested it */
686	if (DEBUG(GRAPH2))
687		Targ_PrintGraph(2);
688
689	Suff_End();
690        Targ_End();
691	Arch_End();
692	str_end();
693	Var_End();
694	Parse_End();
695	Dir_End();
696
697	if (queryFlag && outOfDate)
698		return(1);
699	else
700		return(0);
701}
702
703/*-
704 * ReadMakefile  --
705 *	Open and parse the given makefile.
706 *
707 * Results:
708 *	TRUE if ok. FALSE if couldn't open file.
709 *
710 * Side Effects:
711 *	lots
712 */
713static Boolean
714ReadMakefile(fname)
715	char *fname;		/* makefile to read */
716{
717	extern Lst parseIncPath, sysIncPath;
718	FILE *stream;
719	char *name, path[MAXPATHLEN + 1];
720
721	if (!strcmp(fname, "-")) {
722		Parse_File("(stdin)", stdin);
723		Var_Set("MAKEFILE", "", VAR_GLOBAL);
724	} else {
725		if ((stream = fopen(fname, "r")) != NULL)
726			goto found;
727		/* if we've chdir'd, rebuild the path name */
728		if (curdir != objdir && *fname != '/') {
729			(void)sprintf(path, "%s/%s", curdir, fname);
730			if ((stream = fopen(path, "r")) != NULL) {
731				fname = path;
732				goto found;
733			}
734		}
735		/* look in -I and system include directories. */
736		name = Dir_FindFile(fname, parseIncPath);
737		if (!name)
738			name = Dir_FindFile(fname, sysIncPath);
739		if (!name || !(stream = fopen(name, "r")))
740			return(FALSE);
741		fname = name;
742		/*
743		 * set the MAKEFILE variable desired by System V fans -- the
744		 * placement of the setting here means it gets set to the last
745		 * makefile specified, as it is set by SysV make.
746		 */
747found:		Var_Set("MAKEFILE", fname, VAR_GLOBAL);
748		Parse_File(fname, stream);
749		(void)fclose(stream);
750	}
751	return(TRUE);
752}
753
754/*-
755 * Error --
756 *	Print an error message given its format.
757 *
758 * Results:
759 *	None.
760 *
761 * Side Effects:
762 *	The message is printed.
763 */
764/* VARARGS */
765void
766#if __STDC__
767Error(char *fmt, ...)
768#else
769Error(va_alist)
770	va_dcl
771#endif
772{
773	va_list ap;
774#if __STDC__
775	va_start(ap, fmt);
776#else
777	char *fmt;
778
779	va_start(ap);
780	fmt = va_arg(ap, char *);
781#endif
782	(void)vfprintf(stderr, fmt, ap);
783	va_end(ap);
784	(void)fprintf(stderr, "\n");
785	(void)fflush(stderr);
786}
787
788/*-
789 * Fatal --
790 *	Produce a Fatal error message. If jobs are running, waits for them
791 *	to finish.
792 *
793 * Results:
794 *	None
795 *
796 * Side Effects:
797 *	The program exits
798 */
799/* VARARGS */
800void
801#if __STDC__
802Fatal(char *fmt, ...)
803#else
804Fatal(va_alist)
805	va_dcl
806#endif
807{
808	va_list ap;
809#if __STDC__
810	va_start(ap, fmt);
811#else
812	char *fmt;
813
814	va_start(ap);
815	fmt = va_arg(ap, char *);
816#endif
817	if (jobsRunning)
818		Job_Wait();
819
820	(void)vfprintf(stderr, fmt, ap);
821	va_end(ap);
822	(void)fprintf(stderr, "\n");
823	(void)fflush(stderr);
824
825	if (DEBUG(GRAPH2))
826		Targ_PrintGraph(2);
827	exit(2);		/* Not 1 so -q can distinguish error */
828}
829
830/*
831 * Punt --
832 *	Major exception once jobs are being created. Kills all jobs, prints
833 *	a message and exits.
834 *
835 * Results:
836 *	None
837 *
838 * Side Effects:
839 *	All children are killed indiscriminately and the program Lib_Exits
840 */
841/* VARARGS */
842void
843#if __STDC__
844Punt(char *fmt, ...)
845#else
846Punt(va_alist)
847	va_dcl
848#endif
849{
850	va_list ap;
851#if __STDC__
852	va_start(ap, fmt);
853#else
854	char *fmt;
855
856	va_start(ap);
857	fmt = va_arg(ap, char *);
858#endif
859
860	(void)fprintf(stderr, "make: ");
861	(void)vfprintf(stderr, fmt, ap);
862	va_end(ap);
863	(void)fprintf(stderr, "\n");
864	(void)fflush(stderr);
865
866	DieHorribly();
867}
868
869/*-
870 * DieHorribly --
871 *	Exit without giving a message.
872 *
873 * Results:
874 *	None
875 *
876 * Side Effects:
877 *	A big one...
878 */
879void
880DieHorribly()
881{
882	if (jobsRunning)
883		Job_AbortAll();
884	if (DEBUG(GRAPH2))
885		Targ_PrintGraph(2);
886	exit(2);		/* Not 1, so -q can distinguish error */
887}
888
889/*
890 * Finish --
891 *	Called when aborting due to errors in child shell to signal
892 *	abnormal exit.
893 *
894 * Results:
895 *	None
896 *
897 * Side Effects:
898 *	The program exits
899 */
900void
901Finish(errors)
902	int errors;	/* number of errors encountered in Make_Make */
903{
904	Fatal("%d error%s", errors, errors == 1 ? "" : "s");
905}
906
907/*
908 * emalloc --
909 *	malloc, but die on error.
910 */
911char *
912emalloc(len)
913	size_t len;
914{
915	char *p;
916
917	if ((p = (char *) malloc(len)) == NULL)
918		enomem();
919	return(p);
920}
921
922/*
923 * enomem --
924 *	die when out of memory.
925 */
926void
927enomem()
928{
929	(void)fprintf(stderr, "make: %s.\n", strerror(errno));
930	exit(2);
931}
932
933/*
934 * usage --
935 *	exit with usage message
936 */
937static void
938usage()
939{
940	(void)fprintf(stderr,
941"usage: make [-eiknqrst] [-D variable] [-d flags] [-f makefile ]\n\
942            [-I directory] [-j max_jobs] [variable=value]\n");
943	exit(2);
944}
945
946
947int
948PrintAddr(a, b)
949    ClientData a;
950    ClientData b;
951{
952    printf("%lx ", (unsigned long) a);
953    return b ? 0 : 0;
954}
955