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