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