main.c revision 16663
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	char *realobjdir;	/* Where we'd like to go */
379	struct utsname utsname;
380    	char *machine = getenv("MACHINE");
381
382	/*
383	 * Find where we are and take care of PWD for the automounter...
384	 * All this code is so that we know where we are when we start up
385	 * on a different machine with pmake.
386	 */
387	curdir = cdpath;
388	if (getcwd(curdir, MAXPATHLEN) == NULL) {
389		(void)fprintf(stderr, "make: %s.\n", strerror(errno));
390		exit(2);
391	}
392
393	if (stat(curdir, &sa) == -1) {
394	    (void)fprintf(stderr, "make: %s: %s.\n",
395			  curdir, strerror(errno));
396	    exit(2);
397	}
398
399	if ((pwd = getenv("PWD")) != NULL) {
400	    if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
401		sa.st_dev == sb.st_dev)
402		(void) strcpy(curdir, pwd);
403	}
404
405	/*
406	 * Get the name of this type of MACHINE from utsname
407	 * so we can share an executable for similar machines.
408	 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
409	 *
410	 * Note that while MACHINE is decided at run-time,
411	 * MACHINE_ARCH is always known at compile time.
412	 */
413    	if (!machine) {
414	    if (uname(&utsname)) {
415		    perror("make: uname");
416		    exit(2);
417	    }
418	    machine = utsname.machine;
419	}
420
421	/*
422	 * if the MAKEOBJDIR (or by default, the _PATH_OBJDIR) directory
423	 * exists, change into it and build there.  Once things are
424	 * initted, have to add the original directory to the search path,
425	 * and modify the paths for the Makefiles apropriately.  The
426	 * current directory is also placed as a variable for make scripts.
427	 */
428	if (!(path = getenv("MAKEOBJDIR")))
429		path = _PATH_OBJDIR;
430	(void) snprintf(mdpath, MAXPATHLEN, "%s%s", path, curdir);
431	realobjdir = mdpath;	/* This is where we'd _like_ to be, anyway */
432
433	if (stat(mdpath, &sb) == 0 && S_ISDIR(sb.st_mode)) {
434
435		if (chdir(mdpath)) {
436			(void)fprintf(stderr, "make warning: %s: %s.\n",
437				      mdpath, strerror(errno));
438			objdir = curdir;
439		}
440		else {
441			if (mdpath[0] != '/') {
442				(void) sprintf(obpath, "%s/%s", curdir, mdpath);
443				objdir = obpath;
444			}
445			else
446				objdir = mdpath;
447		}
448	}
449	else
450		objdir = curdir;
451
452	setenv("PWD", objdir, 1);
453
454	create = Lst_Init(FALSE);
455	makefiles = Lst_Init(FALSE);
456	beSilent = FALSE;		/* Print commands as executed */
457	ignoreErrors = FALSE;		/* Pay attention to non-zero returns */
458	noExecute = FALSE;		/* Execute all commands */
459	keepgoing = FALSE;		/* Stop on error */
460	allPrecious = FALSE;		/* Remove targets when interrupted */
461	queryFlag = FALSE;		/* This is not just a check-run */
462	noBuiltins = FALSE;		/* Read the built-in rules */
463	touchFlag = FALSE;		/* Actually update targets */
464	usePipes = TRUE;		/* Catch child output in pipes */
465	debug = 0;			/* No debug verbosity, please. */
466	jobsRunning = FALSE;
467
468	maxJobs = DEFMAXJOBS;		/* Set default max concurrency */
469	maxLocal = DEFMAXLOCAL;		/* Set default local max concurrency */
470#ifdef notyet
471	compatMake = FALSE;		/* No compat mode */
472#else
473	compatMake = TRUE;		/* No compat mode */
474#endif
475
476
477	/*
478	 * Initialize the parsing, directory and variable modules to prepare
479	 * for the reading of inclusion paths and variable settings on the
480	 * command line
481	 */
482	Dir_Init();		/* Initialize directory structures so -I flags
483				 * can be processed correctly */
484	Parse_Init();		/* Need to initialize the paths of #include
485				 * directories */
486	Var_Init();		/* As well as the lists of variables for
487				 * parsing arguments */
488        str_init();
489	if (objdir != curdir)
490		Dir_AddDir(dirSearchPath, curdir);
491	Var_Set(".CURDIR", curdir, VAR_GLOBAL);
492	Var_Set(".TARGETOBJDIR", realobjdir, VAR_GLOBAL);
493	Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
494
495	/*
496	 * Initialize various variables.
497	 *	MAKE also gets this name, for compatibility
498	 *	.MAKEFLAGS gets set to the empty string just in case.
499	 *	MFLAGS also gets initialized empty, for compatibility.
500	 */
501	Var_Set("MAKE", argv[0], VAR_GLOBAL);
502	Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
503	Var_Set("MFLAGS", "", VAR_GLOBAL);
504	Var_Set("MACHINE", machine, VAR_GLOBAL);
505#ifdef MACHINE_ARCH
506	Var_Set("MACHINE_ARCH", MACHINE_ARCH, VAR_GLOBAL);
507#endif
508
509	/*
510	 * First snag any flags out of the MAKE environment variable.
511	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
512	 * in a different format).
513	 */
514#ifdef POSIX
515	Main_ParseArgLine(getenv("MAKEFLAGS"));
516#else
517	Main_ParseArgLine(getenv("MAKE"));
518#endif
519
520	MainParseArgs(argc, argv);
521
522	/*
523	 * Initialize archive, target and suffix modules in preparation for
524	 * parsing the makefile(s)
525	 */
526	Arch_Init();
527	Targ_Init();
528	Suff_Init();
529
530	DEFAULT = NILGNODE;
531	(void)time(&now);
532
533	/*
534	 * Set up the .TARGETS variable to contain the list of targets to be
535	 * created. If none specified, make the variable empty -- the parser
536	 * will fill the thing in with the default or .MAIN target.
537	 */
538	if (!Lst_IsEmpty(create)) {
539		LstNode ln;
540
541		for (ln = Lst_First(create); ln != NILLNODE;
542		    ln = Lst_Succ(ln)) {
543			char *name = (char *)Lst_Datum(ln);
544
545			Var_Append(".TARGETS", name, VAR_GLOBAL);
546		}
547	} else
548		Var_Set(".TARGETS", "", VAR_GLOBAL);
549
550	/*
551	 * Read in the built-in rules first, followed by the specified makefile,
552	 * if it was (makefile != (char *) NULL), or the default Makefile and
553	 * makefile, in that order, if it wasn't.
554	 */
555	 if (!noBuiltins && !ReadMakefile(_PATH_DEFSYSMK))
556		Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
557
558	if (!Lst_IsEmpty(makefiles)) {
559		LstNode ln;
560
561		ln = Lst_Find(makefiles, (ClientData)NULL, ReadMakefile);
562		if (ln != NILLNODE)
563			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
564	} else if (!ReadMakefile("makefile"))
565		(void)ReadMakefile("Makefile");
566
567	(void)ReadMakefile(".depend");
568
569	Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
570	if (p1)
571	    free(p1);
572
573	/* Install all the flags into the MAKE envariable. */
574	if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
575#ifdef POSIX
576		setenv("MAKEFLAGS", p, 1);
577#else
578		setenv("MAKE", p, 1);
579#endif
580	if (p1)
581	    free(p1);
582
583	/*
584	 * For compatibility, look at the directories in the VPATH variable
585	 * and add them to the search path, if the variable is defined. The
586	 * variable's value is in the same format as the PATH envariable, i.e.
587	 * <directory>:<directory>:<directory>...
588	 */
589	if (Var_Exists("VPATH", VAR_CMD)) {
590		char *vpath, *path, *cp, savec;
591		/*
592		 * GCC stores string constants in read-only memory, but
593		 * Var_Subst will want to write this thing, so store it
594		 * in an array
595		 */
596		static char VPATH[] = "${VPATH}";
597
598		vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
599		path = vpath;
600		do {
601			/* skip to end of directory */
602			for (cp = path; *cp != ':' && *cp != '\0'; cp++)
603				continue;
604			/* Save terminator character so know when to stop */
605			savec = *cp;
606			*cp = '\0';
607			/* Add directory to search path */
608			Dir_AddDir(dirSearchPath, path);
609			*cp = savec;
610			path = cp + 1;
611		} while (savec == ':');
612		(void)free((Address)vpath);
613	}
614
615	/*
616	 * Now that all search paths have been read for suffixes et al, it's
617	 * time to add the default search path to their lists...
618	 */
619	Suff_DoPaths();
620
621	/* print the initial graph, if the user requested it */
622	if (DEBUG(GRAPH1))
623		Targ_PrintGraph(1);
624
625	/*
626	 * Have now read the entire graph and need to make a list of targets
627	 * to create. If none was given on the command line, we consult the
628	 * parsing module to find the main target(s) to create.
629	 */
630	if (Lst_IsEmpty(create))
631		targs = Parse_MainName();
632	else
633		targs = Targ_FindList(create, TARG_CREATE);
634
635/*
636 * this was original amMake -- want to allow parallelism, so put this
637 * back in, eventually.
638 */
639	if (!compatMake) {
640		/*
641		 * Initialize job module before traversing the graph, now that
642		 * any .BEGIN and .END targets have been read.  This is done
643		 * only if the -q flag wasn't given (to prevent the .BEGIN from
644		 * being executed should it exist).
645		 */
646		if (!queryFlag) {
647			if (maxLocal == -1)
648				maxLocal = maxJobs;
649			Job_Init(maxJobs, maxLocal);
650			jobsRunning = TRUE;
651		}
652
653		/* Traverse the graph, checking on all the targets */
654		outOfDate = Make_Run(targs);
655	} else
656		/*
657		 * Compat_Init will take care of creating all the targets as
658		 * well as initializing the module.
659		 */
660		Compat_Run(targs);
661
662	Lst_Destroy(targs, NOFREE);
663	Lst_Destroy(makefiles, NOFREE);
664	Lst_Destroy(create, (void (*) __P((ClientData))) free);
665
666	/* print the graph now it's been processed if the user requested it */
667	if (DEBUG(GRAPH2))
668		Targ_PrintGraph(2);
669
670	Suff_End();
671        Targ_End();
672	Arch_End();
673	str_end();
674	Var_End();
675	Parse_End();
676	Dir_End();
677
678	if (queryFlag && outOfDate)
679		return(1);
680	else
681		return(0);
682}
683
684/*-
685 * ReadMakefile  --
686 *	Open and parse the given makefile.
687 *
688 * Results:
689 *	TRUE if ok. FALSE if couldn't open file.
690 *
691 * Side Effects:
692 *	lots
693 */
694static Boolean
695ReadMakefile(fname)
696	char *fname;		/* makefile to read */
697{
698	extern Lst parseIncPath, sysIncPath;
699	FILE *stream;
700	char *name, path[MAXPATHLEN + 1];
701
702	if (!strcmp(fname, "-")) {
703		Parse_File("(stdin)", stdin);
704		Var_Set("MAKEFILE", "", VAR_GLOBAL);
705	} else {
706		if ((stream = fopen(fname, "r")) != NULL)
707			goto found;
708		/* if we've chdir'd, rebuild the path name */
709		if (curdir != objdir && *fname != '/') {
710			(void)sprintf(path, "%s/%s", curdir, fname);
711			if ((stream = fopen(path, "r")) != NULL) {
712				fname = path;
713				goto found;
714			}
715		}
716		/* look in -I and system include directories. */
717		name = Dir_FindFile(fname, parseIncPath);
718		if (!name)
719			name = Dir_FindFile(fname, sysIncPath);
720		if (!name || !(stream = fopen(name, "r")))
721			return(FALSE);
722		fname = name;
723		/*
724		 * set the MAKEFILE variable desired by System V fans -- the
725		 * placement of the setting here means it gets set to the last
726		 * makefile specified, as it is set by SysV make.
727		 */
728found:		Var_Set("MAKEFILE", fname, VAR_GLOBAL);
729		Parse_File(fname, stream);
730		(void)fclose(stream);
731	}
732	return(TRUE);
733}
734
735/*-
736 * Error --
737 *	Print an error message given its format.
738 *
739 * Results:
740 *	None.
741 *
742 * Side Effects:
743 *	The message is printed.
744 */
745/* VARARGS */
746void
747#if __STDC__
748Error(char *fmt, ...)
749#else
750Error(va_alist)
751	va_dcl
752#endif
753{
754	va_list ap;
755#if __STDC__
756	va_start(ap, fmt);
757#else
758	char *fmt;
759
760	va_start(ap);
761	fmt = va_arg(ap, char *);
762#endif
763	(void)vfprintf(stderr, fmt, ap);
764	va_end(ap);
765	(void)fprintf(stderr, "\n");
766	(void)fflush(stderr);
767}
768
769/*-
770 * Fatal --
771 *	Produce a Fatal error message. If jobs are running, waits for them
772 *	to finish.
773 *
774 * Results:
775 *	None
776 *
777 * Side Effects:
778 *	The program exits
779 */
780/* VARARGS */
781void
782#if __STDC__
783Fatal(char *fmt, ...)
784#else
785Fatal(va_alist)
786	va_dcl
787#endif
788{
789	va_list ap;
790#if __STDC__
791	va_start(ap, fmt);
792#else
793	char *fmt;
794
795	va_start(ap);
796	fmt = va_arg(ap, char *);
797#endif
798	if (jobsRunning)
799		Job_Wait();
800
801	(void)vfprintf(stderr, fmt, ap);
802	va_end(ap);
803	(void)fprintf(stderr, "\n");
804	(void)fflush(stderr);
805
806	if (DEBUG(GRAPH2))
807		Targ_PrintGraph(2);
808	exit(2);		/* Not 1 so -q can distinguish error */
809}
810
811/*
812 * Punt --
813 *	Major exception once jobs are being created. Kills all jobs, prints
814 *	a message and exits.
815 *
816 * Results:
817 *	None
818 *
819 * Side Effects:
820 *	All children are killed indiscriminately and the program Lib_Exits
821 */
822/* VARARGS */
823void
824#if __STDC__
825Punt(char *fmt, ...)
826#else
827Punt(va_alist)
828	va_dcl
829#endif
830{
831	va_list ap;
832#if __STDC__
833	va_start(ap, fmt);
834#else
835	char *fmt;
836
837	va_start(ap);
838	fmt = va_arg(ap, char *);
839#endif
840
841	(void)fprintf(stderr, "make: ");
842	(void)vfprintf(stderr, fmt, ap);
843	va_end(ap);
844	(void)fprintf(stderr, "\n");
845	(void)fflush(stderr);
846
847	DieHorribly();
848}
849
850/*-
851 * DieHorribly --
852 *	Exit without giving a message.
853 *
854 * Results:
855 *	None
856 *
857 * Side Effects:
858 *	A big one...
859 */
860void
861DieHorribly()
862{
863	if (jobsRunning)
864		Job_AbortAll();
865	if (DEBUG(GRAPH2))
866		Targ_PrintGraph(2);
867	exit(2);		/* Not 1, so -q can distinguish error */
868}
869
870/*
871 * Finish --
872 *	Called when aborting due to errors in child shell to signal
873 *	abnormal exit.
874 *
875 * Results:
876 *	None
877 *
878 * Side Effects:
879 *	The program exits
880 */
881void
882Finish(errors)
883	int errors;	/* number of errors encountered in Make_Make */
884{
885	Fatal("%d error%s", errors, errors == 1 ? "" : "s");
886}
887
888/*
889 * emalloc --
890 *	malloc, but die on error.
891 */
892char *
893emalloc(len)
894	size_t len;
895{
896	char *p;
897
898	if ((p = (char *) malloc(len)) == NULL)
899		enomem();
900	return(p);
901}
902
903/*
904 * enomem --
905 *	die when out of memory.
906 */
907void
908enomem()
909{
910	(void)fprintf(stderr, "make: %s.\n", strerror(errno));
911	exit(2);
912}
913
914/*
915 * usage --
916 *	exit with usage message
917 */
918static void
919usage()
920{
921	(void)fprintf(stderr,
922"usage: make [-eiknqrst] [-D variable] [-d flags] [-f makefile ]\n\
923            [-I directory] [-j max_jobs] [variable=value]\n");
924	exit(2);
925}
926
927
928int
929PrintAddr(a, b)
930    ClientData a;
931    ClientData b;
932{
933    printf("%lx ", (unsigned long) a);
934    return b ? 0 : 0;
935}
936