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