Home | History | Annotate | Line # | Download | only in make
main.c revision 1.53
      1 /*	$NetBSD: main.c,v 1.53 2000/04/16 23:24:23 christos Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1988, 1989, 1990, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      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 #ifdef MAKE_BOOTSTRAP
     42 static char rcsid[] = "$NetBSD: main.c,v 1.53 2000/04/16 23:24:23 christos Exp $";
     43 #else
     44 #include <sys/cdefs.h>
     45 #ifndef lint
     46 __COPYRIGHT("@(#) Copyright (c) 1988, 1989, 1990, 1993\n\
     47 	The Regents of the University of California.  All rights reserved.\n");
     48 #endif /* not lint */
     49 
     50 #ifndef lint
     51 #if 0
     52 static char sccsid[] = "@(#)main.c	8.3 (Berkeley) 3/19/94";
     53 #else
     54 __RCSID("$NetBSD: main.c,v 1.53 2000/04/16 23:24:23 christos Exp $");
     55 #endif
     56 #endif /* not lint */
     57 #endif
     58 
     59 /*-
     60  * main.c --
     61  *	The main file for this entire program. Exit routines etc
     62  *	reside here.
     63  *
     64  * Utility functions defined in this file:
     65  *	Main_ParseArgLine	Takes a line of arguments, breaks them and
     66  *				treats them as if they were given when first
     67  *				invoked. Used by the parse module to implement
     68  *				the .MFLAGS target.
     69  *
     70  *	Error			Print a tagged error message. The global
     71  *				MAKE variable must have been defined. This
     72  *				takes a format string and two optional
     73  *				arguments for it.
     74  *
     75  *	Fatal			Print an error message and exit. Also takes
     76  *				a format string and two arguments.
     77  *
     78  *	Punt			Aborts all jobs and exits with a message. Also
     79  *				takes a format string and two arguments.
     80  *
     81  *	Finish			Finish things up by printing the number of
     82  *				errors which occured, as passed to it, and
     83  *				exiting.
     84  */
     85 
     86 #include <sys/types.h>
     87 #include <sys/time.h>
     88 #include <sys/param.h>
     89 #include <sys/resource.h>
     90 #include <sys/signal.h>
     91 #include <sys/stat.h>
     92 #ifndef MAKE_BOOTSTRAP
     93 #include <sys/utsname.h>
     94 #endif
     95 #include <sys/wait.h>
     96 #include <errno.h>
     97 #include <fcntl.h>
     98 #include <stdio.h>
     99 #include <stdlib.h>
    100 #include <time.h>
    101 #ifdef __STDC__
    102 #include <stdarg.h>
    103 #else
    104 #include <varargs.h>
    105 #endif
    106 #include "make.h"
    107 #include "hash.h"
    108 #include "dir.h"
    109 #include "job.h"
    110 #include "pathnames.h"
    111 
    112 #ifndef	DEFMAXLOCAL
    113 #define	DEFMAXLOCAL DEFMAXJOBS
    114 #endif	/* DEFMAXLOCAL */
    115 
    116 #define	MAKEFLAGS	".MAKEFLAGS"
    117 
    118 Lst			create;		/* Targets to be made */
    119 time_t			now;		/* Time at start of make */
    120 GNode			*DEFAULT;	/* .DEFAULT node */
    121 Boolean			allPrecious;	/* .PRECIOUS given on line by itself */
    122 
    123 static Boolean		noBuiltins;	/* -r flag */
    124 static Lst		makefiles;	/* ordered list of makefiles to read */
    125 static Boolean		printVars;	/* print value of one or more vars */
    126 static Lst		variables;	/* list of variables to print */
    127 int			maxJobs;	/* -j argument */
    128 static int		maxLocal;	/* -L argument */
    129 Boolean			compatMake;	/* -B argument */
    130 Boolean			debug;		/* -d flag */
    131 Boolean			noExecute;	/* -n flag */
    132 Boolean			keepgoing;	/* -k flag */
    133 Boolean			queryFlag;	/* -q flag */
    134 Boolean			touchFlag;	/* -t flag */
    135 Boolean			usePipes;	/* !-P flag */
    136 Boolean			ignoreErrors;	/* -i flag */
    137 Boolean			beSilent;	/* -s flag */
    138 Boolean			oldVars;	/* variable substitution style */
    139 Boolean			checkEnvFirst;	/* -e flag */
    140 Boolean			mkIncPath;	/* -m flag */
    141 static Boolean		jobsRunning;	/* TRUE if the jobs might be running */
    142 
    143 static void		MainParseArgs __P((int, char **));
    144 char *			chdir_verify_path __P((char *, char *));
    145 static int		ReadMakefile __P((ClientData, ClientData));
    146 static void		usage __P((void));
    147 
    148 static char *curdir;			/* startup directory */
    149 static char *objdir;			/* where we chdir'ed to */
    150 static char *progname;			/* the program name */
    151 
    152 /*-
    153  * MainParseArgs --
    154  *	Parse a given argument vector. Called from main() and from
    155  *	Main_ParseArgLine() when the .MAKEFLAGS target is used.
    156  *
    157  *	XXX: Deal with command line overriding .MAKEFLAGS in makefile
    158  *
    159  * Results:
    160  *	None
    161  *
    162  * Side Effects:
    163  *	Various global and local flags will be set depending on the flags
    164  *	given
    165  */
    166 static void
    167 MainParseArgs(argc, argv)
    168 	int argc;
    169 	char **argv;
    170 {
    171 	char *p;
    172 	int c;
    173 	int forceJobs = 0;
    174 
    175 	optind = 1;	/* since we're called more than once */
    176 #ifdef REMOTE
    177 # define OPTFLAGS "BD:I:L:PSV:d:ef:ij:km:nqrst"
    178 #else
    179 # define OPTFLAGS "BD:I:PSV:d:ef:ij:km:nqrst"
    180 #endif
    181 rearg:	while((c = getopt(argc, argv, OPTFLAGS)) != -1) {
    182 		switch(c) {
    183 		case 'D':
    184 			Var_Set(optarg, "1", VAR_GLOBAL);
    185 			Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
    186 			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
    187 			break;
    188 		case 'I':
    189 			Parse_AddIncludeDir(optarg);
    190 			Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
    191 			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
    192 			break;
    193 		case 'V':
    194 			printVars = TRUE;
    195 			(void)Lst_AtEnd(variables, (ClientData)optarg);
    196 			Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
    197 			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
    198 			break;
    199 		case 'B':
    200 			compatMake = TRUE;
    201 			break;
    202 #ifdef REMOTE
    203 		case 'L':
    204 			maxLocal = strtol(optarg, &p, 0);
    205 			if (*p != '\0' || maxLocal < 1) {
    206 				(void) fprintf(stderr, "make: illegal argument to -L -- must be positive integer!\n");
    207 				exit(1);
    208 			}
    209 			Var_Append(MAKEFLAGS, "-L", VAR_GLOBAL);
    210 			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
    211 			break;
    212 #endif
    213 		case 'P':
    214 			usePipes = FALSE;
    215 			Var_Append(MAKEFLAGS, "-P", VAR_GLOBAL);
    216 			break;
    217 		case 'S':
    218 			keepgoing = FALSE;
    219 			Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
    220 			break;
    221 		case 'd': {
    222 			char *modules = optarg;
    223 
    224 			for (; *modules; ++modules)
    225 				switch (*modules) {
    226 				case 'A':
    227 					debug = ~0;
    228 					break;
    229 				case 'a':
    230 					debug |= DEBUG_ARCH;
    231 					break;
    232 				case 'c':
    233 					debug |= DEBUG_COND;
    234 					break;
    235 				case 'd':
    236 					debug |= DEBUG_DIR;
    237 					break;
    238 				case 'f':
    239 					debug |= DEBUG_FOR;
    240 					break;
    241 				case 'g':
    242 					if (modules[1] == '1') {
    243 						debug |= DEBUG_GRAPH1;
    244 						++modules;
    245 					}
    246 					else if (modules[1] == '2') {
    247 						debug |= DEBUG_GRAPH2;
    248 						++modules;
    249 					}
    250 					break;
    251 				case 'j':
    252 					debug |= DEBUG_JOB;
    253 					break;
    254 				case 'm':
    255 					debug |= DEBUG_MAKE;
    256 					break;
    257 				case 's':
    258 					debug |= DEBUG_SUFF;
    259 					break;
    260 				case 't':
    261 					debug |= DEBUG_TARG;
    262 					break;
    263 				case 'v':
    264 					debug |= DEBUG_VAR;
    265 					break;
    266 				default:
    267 					(void)fprintf(stderr,
    268 				"make: illegal argument to d option -- %c\n",
    269 					    *modules);
    270 					usage();
    271 				}
    272 			Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
    273 			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
    274 			break;
    275 		}
    276 		case 'e':
    277 			checkEnvFirst = TRUE;
    278 			Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
    279 			break;
    280 		case 'f':
    281 			(void)Lst_AtEnd(makefiles, (ClientData)optarg);
    282 			break;
    283 		case 'i':
    284 			ignoreErrors = TRUE;
    285 			Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
    286 			break;
    287 		case 'j':
    288 			forceJobs = TRUE;
    289 			maxJobs = strtol(optarg, &p, 0);
    290 			if (*p != '\0' || maxJobs < 1) {
    291 				(void) fprintf(stderr, "make: illegal argument to -j -- must be positive integer!\n");
    292 				exit(1);
    293 			}
    294 #ifndef REMOTE
    295 			maxLocal = maxJobs;
    296 #endif
    297 			Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
    298 			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
    299 			break;
    300 		case 'k':
    301 			keepgoing = TRUE;
    302 			Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
    303 			break;
    304 		case 'm':
    305 			mkIncPath = TRUE;
    306 			(void) Dir_AddDir(sysIncPath, optarg);
    307 			Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
    308 			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
    309 			break;
    310 		case 'n':
    311 			noExecute = TRUE;
    312 			Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
    313 			break;
    314 		case 'q':
    315 			queryFlag = TRUE;
    316 			/* Kind of nonsensical, wot? */
    317 			Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
    318 			break;
    319 		case 'r':
    320 			noBuiltins = TRUE;
    321 			Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
    322 			break;
    323 		case 's':
    324 			beSilent = TRUE;
    325 			Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
    326 			break;
    327 		case 't':
    328 			touchFlag = TRUE;
    329 			Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
    330 			break;
    331 		default:
    332 		case '?':
    333 			usage();
    334 		}
    335 	}
    336 
    337 	/*
    338 	 * Be compatible if user did not specify -j and did not explicitly
    339 	 * turned compatibility on
    340 	 */
    341 	if (!compatMake && !forceJobs)
    342 		compatMake = TRUE;
    343 
    344 	oldVars = TRUE;
    345 
    346 	/*
    347 	 * See if the rest of the arguments are variable assignments and
    348 	 * perform them if so. Else take them to be targets and stuff them
    349 	 * on the end of the "create" list.
    350 	 */
    351 	for (argv += optind, argc -= optind; *argv; ++argv, --argc)
    352 		if (Parse_IsVar(*argv))
    353 			Parse_DoVar(*argv, VAR_CMD);
    354 		else {
    355 			if (!**argv)
    356 				Punt("illegal (null) argument.");
    357 			if (**argv == '-') {
    358 				if ((*argv)[1])
    359 					optind = 0;     /* -flag... */
    360 				else
    361 					optind = 1;     /* - */
    362 				goto rearg;
    363 			}
    364 			(void)Lst_AtEnd(create, (ClientData)estrdup(*argv));
    365 		}
    366 }
    367 
    368 /*-
    369  * Main_ParseArgLine --
    370  *  	Used by the parse module when a .MFLAGS or .MAKEFLAGS target
    371  *	is encountered and by main() when reading the .MAKEFLAGS envariable.
    372  *	Takes a line of arguments and breaks it into its
    373  * 	component words and passes those words and the number of them to the
    374  *	MainParseArgs function.
    375  *	The line should have all its leading whitespace removed.
    376  *
    377  * Results:
    378  *	None
    379  *
    380  * Side Effects:
    381  *	Only those that come from the various arguments.
    382  */
    383 void
    384 Main_ParseArgLine(line)
    385 	char *line;			/* Line to fracture */
    386 {
    387 	char **argv;			/* Manufactured argument vector */
    388 	int argc;			/* Number of arguments in argv */
    389 	char *args;			/* Space used by the args */
    390 	char *buf, *p1;
    391 	char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
    392 	size_t len;
    393 
    394 	if (line == NULL)
    395 		return;
    396 	for (; *line == ' '; ++line)
    397 		continue;
    398 	if (!*line)
    399 		return;
    400 
    401 	buf = emalloc(len = strlen(line) + strlen(argv0) + 2);
    402 	(void)snprintf(buf, len, "%s %s", argv0, line);
    403 	if (p1)
    404 		free(p1);
    405 
    406 	argv = brk_string(buf, &argc, TRUE, &args);
    407 	free(buf);
    408 	MainParseArgs(argc, argv);
    409 
    410 	free(args);
    411 	free(argv);
    412 }
    413 
    414 char *
    415 chdir_verify_path(path, obpath)
    416 	char *path;
    417 	char *obpath;
    418 {
    419 	struct stat sb;
    420 
    421 	if (strchr(path, '$') != 0) {
    422 		path = Var_Subst(NULL, path, VAR_GLOBAL, 0);
    423 	}
    424 	if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
    425 		if (chdir(path)) {
    426 			(void)fprintf(stderr, "make warning: %s: %s.\n",
    427 				      path, strerror(errno));
    428 			return 0;
    429 		}
    430 		else {
    431 			if (path[0] != '/') {
    432 				(void) snprintf(obpath, MAXPATHLEN, "%s/%s",
    433 						curdir, path);
    434 				return obpath;
    435 			}
    436 			else
    437 				return path;
    438 		}
    439 	}
    440 
    441 	return 0;
    442 }
    443 
    444 
    445 /*-
    446  * main --
    447  *	The main function, for obvious reasons. Initializes variables
    448  *	and a few modules, then parses the arguments give it in the
    449  *	environment and on the command line. Reads the system makefile
    450  *	followed by either Makefile, makefile or the file given by the
    451  *	-f argument. Sets the .MAKEFLAGS PMake variable based on all the
    452  *	flags it has received by then uses either the Make or the Compat
    453  *	module to create the initial list of targets.
    454  *
    455  * Results:
    456  *	If -q was given, exits -1 if anything was out-of-date. Else it exits
    457  *	0.
    458  *
    459  * Side Effects:
    460  *	The program exits when done. Targets are created. etc. etc. etc.
    461  */
    462 int
    463 main(argc, argv)
    464 	int argc;
    465 	char **argv;
    466 {
    467 	Lst targs;	/* target nodes to create -- passed to Make_Init */
    468 	Boolean outOfDate = TRUE; 	/* FALSE if all targets up to date */
    469 	struct stat sb, sa;
    470 	char *p, *p1, *path, *pathp, *pwd;
    471 	char mdpath[MAXPATHLEN + 1];
    472 	char obpath[MAXPATHLEN + 1];
    473 	char cdpath[MAXPATHLEN + 1];
    474     	char *machine = getenv("MACHINE");
    475 	char *machine_arch = getenv("MACHINE_ARCH");
    476 	Lst sysMkPath;			/* Path of sys.mk */
    477 	char *cp = NULL, *start;
    478 					/* avoid faults on read-only strings */
    479 	static char syspath[] = _PATH_DEFSYSPATH;
    480 
    481 	if ((progname = strrchr(argv[0], '/')) != NULL)
    482 		progname++;
    483 	else
    484 		progname = argv[0];
    485 #ifdef RLIMIT_NOFILE
    486 	/*
    487 	 * get rid of resource limit on file descriptors
    488 	 */
    489 	{
    490 		struct rlimit rl;
    491 		if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
    492 		    rl.rlim_cur != rl.rlim_max) {
    493 			rl.rlim_cur = rl.rlim_max;
    494 			(void) setrlimit(RLIMIT_NOFILE, &rl);
    495 		}
    496 	}
    497 #endif
    498 	/*
    499 	 * Find where we are and take care of PWD for the automounter...
    500 	 * All this code is so that we know where we are when we start up
    501 	 * on a different machine with pmake.
    502 	 */
    503 	curdir = cdpath;
    504 	if (getcwd(curdir, MAXPATHLEN) == NULL) {
    505 		(void)fprintf(stderr, "make: %s.\n", strerror(errno));
    506 		exit(2);
    507 	}
    508 
    509 	if (stat(curdir, &sa) == -1) {
    510 	    (void)fprintf(stderr, "make: %s: %s.\n",
    511 			  curdir, strerror(errno));
    512 	    exit(2);
    513 	}
    514 
    515 	if ((pwd = getenv("PWD")) != NULL) {
    516 	    if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
    517 		sa.st_dev == sb.st_dev)
    518 		(void) strcpy(curdir, pwd);
    519 	}
    520 
    521 	/*
    522 	 * Get the name of this type of MACHINE from utsname
    523 	 * so we can share an executable for similar machines.
    524 	 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
    525 	 *
    526 	 * Note that both MACHINE and MACHINE_ARCH are decided at
    527 	 * run-time.
    528 	 */
    529 	if (!machine) {
    530 #ifndef MAKE_BOOTSTRAP
    531 	    struct utsname utsname;
    532 
    533 	    if (uname(&utsname) == -1) {
    534 		    perror("make: uname");
    535 		    exit(2);
    536 	    }
    537 	    machine = utsname.machine;
    538 #else
    539 	    machine = MACHINE;
    540 #endif
    541 	}
    542 
    543 	if (!machine_arch) {
    544 #ifndef MACHINE_ARCH
    545 #ifdef __ARCHITECTURE__
    546             machine_arch = __ARCHITECTURE__;
    547 #else
    548 	    machine_arch = "unknown";	/* XXX: no uname -p yet */
    549 #endif
    550 #else
    551 	    machine_arch = MACHINE_ARCH;
    552 #endif
    553 	}
    554 
    555 	/*
    556 	 * Just in case MAKEOBJDIR wants us to do something tricky.
    557 	 */
    558 	Var_Init();		/* Initialize the lists of variables for
    559 				 * parsing arguments */
    560 	Var_Set(".CURDIR", curdir, VAR_GLOBAL);
    561 	Var_Set("MACHINE", machine, VAR_GLOBAL);
    562 	Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
    563 
    564 	/*
    565 	 * If the MAKEOBJDIR (or by default, the _PATH_OBJDIR) directory
    566 	 * exists, change into it and build there.  (If a .${MACHINE} suffix
    567 	 * exists, use that directory instead).
    568 	 * Otherwise check MAKEOBJDIRPREFIX`cwd` (or by default,
    569 	 * _PATH_OBJDIRPREFIX`cwd`) and build there if it exists.
    570 	 * If all fails, use the current directory to build.
    571 	 *
    572 	 * Once things are initted,
    573 	 * have to add the original directory to the search path,
    574 	 * and modify the paths for the Makefiles apropriately.  The
    575 	 * current directory is also placed as a variable for make scripts.
    576 	 */
    577 	if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
    578 		if (!(path = getenv("MAKEOBJDIR"))) {
    579 			path = _PATH_OBJDIR;
    580 			pathp = _PATH_OBJDIRPREFIX;
    581 			(void) snprintf(mdpath, MAXPATHLEN, "%s.%s",
    582 					path, machine);
    583 			if (!(objdir = chdir_verify_path(mdpath, obpath)))
    584 				if (!(objdir=chdir_verify_path(path, obpath))) {
    585 					(void) snprintf(mdpath, MAXPATHLEN,
    586 							"%s%s", pathp, curdir);
    587 					if (!(objdir=chdir_verify_path(mdpath,
    588 								       obpath)))
    589 						objdir = curdir;
    590 				}
    591 		}
    592 		else if (!(objdir = chdir_verify_path(path, obpath)))
    593 			objdir = curdir;
    594 	}
    595 	else {
    596 		(void) snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
    597 		if (!(objdir = chdir_verify_path(mdpath, obpath)))
    598 			objdir = curdir;
    599 	}
    600 
    601 	setenv("PWD", objdir, 1);
    602 
    603 	create = Lst_Init(FALSE);
    604 	makefiles = Lst_Init(FALSE);
    605 	printVars = FALSE;
    606 	variables = Lst_Init(FALSE);
    607 	beSilent = FALSE;		/* Print commands as executed */
    608 	ignoreErrors = FALSE;		/* Pay attention to non-zero returns */
    609 	noExecute = FALSE;		/* Execute all commands */
    610 	keepgoing = FALSE;		/* Stop on error */
    611 	allPrecious = FALSE;		/* Remove targets when interrupted */
    612 	queryFlag = FALSE;		/* This is not just a check-run */
    613 	noBuiltins = FALSE;		/* Read the built-in rules */
    614 	touchFlag = FALSE;		/* Actually update targets */
    615 	usePipes = TRUE;		/* Catch child output in pipes */
    616 	debug = 0;			/* No debug verbosity, please. */
    617 	jobsRunning = FALSE;
    618 
    619 	maxLocal = DEFMAXLOCAL;		/* Set default local max concurrency */
    620 #ifdef REMOTE
    621 	maxJobs = DEFMAXJOBS;		/* Set default max concurrency */
    622 #else
    623 	maxJobs = maxLocal;
    624 #endif
    625 	compatMake = FALSE;		/* No compat mode */
    626 
    627 
    628 	/*
    629 	 * Initialize the parsing, directory and variable modules to prepare
    630 	 * for the reading of inclusion paths and variable settings on the
    631 	 * command line
    632 	 */
    633 
    634 	/*
    635 	 * Initialize directory structures so -I flags can be processed
    636 	 * correctly, if we have a different objdir, then let the directory
    637 	 * know our curdir.
    638 	 */
    639 	Dir_Init(curdir != objdir ? curdir : NULL);
    640 	Parse_Init();		/* Need to initialize the paths of #include
    641 				 * directories */
    642 	Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
    643 
    644 	/*
    645 	 * Initialize various variables.
    646 	 *	MAKE also gets this name, for compatibility
    647 	 *	.MAKEFLAGS gets set to the empty string just in case.
    648 	 *	MFLAGS also gets initialized empty, for compatibility.
    649 	 */
    650 	Var_Set("MAKE", argv[0], VAR_GLOBAL);
    651 	Var_Set(".MAKE", argv[0], VAR_GLOBAL);
    652 	Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
    653 	Var_Set("MFLAGS", "", VAR_GLOBAL);
    654 
    655 	/*
    656 	 * First snag any flags out of the MAKE environment variable.
    657 	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
    658 	 * in a different format).
    659 	 */
    660 #ifdef POSIX
    661 	Main_ParseArgLine(getenv("MAKEFLAGS"));
    662 #else
    663 	Main_ParseArgLine(getenv("MAKE"));
    664 #endif
    665 
    666 	MainParseArgs(argc, argv);
    667 
    668 	/*
    669 	 * Initialize archive, target and suffix modules in preparation for
    670 	 * parsing the makefile(s)
    671 	 */
    672 	Arch_Init();
    673 	Targ_Init();
    674 	Suff_Init();
    675 
    676 	DEFAULT = NILGNODE;
    677 	(void)time(&now);
    678 
    679 	/*
    680 	 * Set up the .TARGETS variable to contain the list of targets to be
    681 	 * created. If none specified, make the variable empty -- the parser
    682 	 * will fill the thing in with the default or .MAIN target.
    683 	 */
    684 	if (!Lst_IsEmpty(create)) {
    685 		LstNode ln;
    686 
    687 		for (ln = Lst_First(create); ln != NILLNODE;
    688 		    ln = Lst_Succ(ln)) {
    689 			char *name = (char *)Lst_Datum(ln);
    690 
    691 			Var_Append(".TARGETS", name, VAR_GLOBAL);
    692 		}
    693 	} else
    694 		Var_Set(".TARGETS", "", VAR_GLOBAL);
    695 
    696 
    697 	/*
    698 	 * If no user-supplied system path was given (through the -m option)
    699 	 * add the directories from the DEFSYSPATH (more than one may be given
    700 	 * as dir1:...:dirn) to the system include path.
    701 	 */
    702 	if (!mkIncPath) {
    703 		for (start = syspath; *start != '\0'; start = cp) {
    704 			for (cp = start; *cp != '\0' && *cp != ':'; cp++)
    705 				continue;
    706 			if (*cp == '\0') {
    707 				(void) Dir_AddDir(sysIncPath, start);
    708 			} else {
    709 				*cp++ = '\0';
    710 				(void) Dir_AddDir(sysIncPath, start);
    711 			}
    712 		}
    713 	}
    714 
    715 	/*
    716 	 * Read in the built-in rules first, followed by the specified
    717 	 * makefile, if it was (makefile != (char *) NULL), or the default
    718 	 * Makefile and makefile, in that order, if it wasn't.
    719 	 */
    720 	if (!noBuiltins) {
    721 		LstNode ln;
    722 
    723 		sysMkPath = Lst_Init (FALSE);
    724 		Dir_Expand (_PATH_DEFSYSMK, sysIncPath, sysMkPath);
    725 		if (Lst_IsEmpty(sysMkPath))
    726 			Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
    727 		ln = Lst_Find(sysMkPath, (ClientData)NULL, ReadMakefile);
    728 		if (ln != NILLNODE)
    729 			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
    730 	}
    731 
    732 	if (!Lst_IsEmpty(makefiles)) {
    733 		LstNode ln;
    734 
    735 		ln = Lst_Find(makefiles, (ClientData)NULL, ReadMakefile);
    736 		if (ln != NILLNODE)
    737 			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
    738 	} else if (!ReadMakefile("makefile", NULL))
    739 		(void)ReadMakefile("Makefile", NULL);
    740 
    741 	(void)ReadMakefile(".depend", NULL);
    742 
    743 	Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
    744 	if (p1)
    745 	    free(p1);
    746 
    747 	/* Install all the flags into the MAKE envariable. */
    748 	if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
    749 #ifdef POSIX
    750 		setenv("MAKEFLAGS", p, 1);
    751 #else
    752 		setenv("MAKE", p, 1);
    753 #endif
    754 	if (p1)
    755 	    free(p1);
    756 
    757 	/*
    758 	 * For compatibility, look at the directories in the VPATH variable
    759 	 * and add them to the search path, if the variable is defined. The
    760 	 * variable's value is in the same format as the PATH envariable, i.e.
    761 	 * <directory>:<directory>:<directory>...
    762 	 */
    763 	if (Var_Exists("VPATH", VAR_CMD)) {
    764 		char *vpath, *path, *cp, savec;
    765 		/*
    766 		 * GCC stores string constants in read-only memory, but
    767 		 * Var_Subst will want to write this thing, so store it
    768 		 * in an array
    769 		 */
    770 		static char VPATH[] = "${VPATH}";
    771 
    772 		vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
    773 		path = vpath;
    774 		do {
    775 			/* skip to end of directory */
    776 			for (cp = path; *cp != ':' && *cp != '\0'; cp++)
    777 				continue;
    778 			/* Save terminator character so know when to stop */
    779 			savec = *cp;
    780 			*cp = '\0';
    781 			/* Add directory to search path */
    782 			(void) Dir_AddDir(dirSearchPath, path);
    783 			*cp = savec;
    784 			path = cp + 1;
    785 		} while (savec == ':');
    786 		(void)free((Address)vpath);
    787 	}
    788 
    789 	/*
    790 	 * Now that all search paths have been read for suffixes et al, it's
    791 	 * time to add the default search path to their lists...
    792 	 */
    793 	Suff_DoPaths();
    794 
    795 	/*
    796 	 * Propagate attributes through :: dependency lists.
    797 	 */
    798 	Targ_Propagate();
    799 
    800 	/* print the initial graph, if the user requested it */
    801 	if (DEBUG(GRAPH1))
    802 		Targ_PrintGraph(1);
    803 
    804 	/* print the values of any variables requested by the user */
    805 	if (printVars) {
    806 		LstNode ln;
    807 
    808 		for (ln = Lst_First(variables); ln != NILLNODE;
    809 		    ln = Lst_Succ(ln)) {
    810 			char *value = Var_Value((char *)Lst_Datum(ln),
    811 					  VAR_GLOBAL, &p1);
    812 
    813 			printf("%s\n", value ? value : "");
    814 			if (p1)
    815 				free(p1);
    816 		}
    817 	}
    818 
    819 	/*
    820 	 * Have now read the entire graph and need to make a list of targets
    821 	 * to create. If none was given on the command line, we consult the
    822 	 * parsing module to find the main target(s) to create.
    823 	 */
    824 	if (Lst_IsEmpty(create))
    825 		targs = Parse_MainName();
    826 	else
    827 		targs = Targ_FindList(create, TARG_CREATE);
    828 
    829 	if (!compatMake && !printVars) {
    830 		/*
    831 		 * Initialize job module before traversing the graph, now that
    832 		 * any .BEGIN and .END targets have been read.  This is done
    833 		 * only if the -q flag wasn't given (to prevent the .BEGIN from
    834 		 * being executed should it exist).
    835 		 */
    836 		if (!queryFlag) {
    837 			if (maxLocal == -1)
    838 				maxLocal = maxJobs;
    839 			Job_Init(maxJobs, maxLocal);
    840 			jobsRunning = TRUE;
    841 		}
    842 
    843 		/* Traverse the graph, checking on all the targets */
    844 		outOfDate = Make_Run(targs);
    845 	} else if (!printVars) {
    846 		/*
    847 		 * Compat_Init will take care of creating all the targets as
    848 		 * well as initializing the module.
    849 		 */
    850 		Compat_Run(targs);
    851 	}
    852 
    853 #ifdef CLEANUP
    854 	Lst_Destroy(targs, NOFREE);
    855 	Lst_Destroy(variables, NOFREE);
    856 	Lst_Destroy(makefiles, NOFREE);
    857 	Lst_Destroy(create, (void (*) __P((ClientData))) free);
    858 #endif
    859 
    860 	/* print the graph now it's been processed if the user requested it */
    861 	if (DEBUG(GRAPH2))
    862 		Targ_PrintGraph(2);
    863 
    864 	Suff_End();
    865         Targ_End();
    866 	Arch_End();
    867 	Var_End();
    868 	Parse_End();
    869 	Dir_End();
    870 	Job_End();
    871 
    872 	if (queryFlag && outOfDate)
    873 		return(1);
    874 	else
    875 		return(0);
    876 }
    877 
    878 /*-
    879  * ReadMakefile  --
    880  *	Open and parse the given makefile.
    881  *
    882  * Results:
    883  *	TRUE if ok. FALSE if couldn't open file.
    884  *
    885  * Side Effects:
    886  *	lots
    887  */
    888 static Boolean
    889 ReadMakefile(p, q)
    890 	ClientData p, q;
    891 {
    892 	char *fname = p;		/* makefile to read */
    893 	extern Lst parseIncPath;
    894 	FILE *stream;
    895 	size_t len = MAXPATHLEN;
    896 	char *name, *path = emalloc(len);
    897 
    898 	if (!strcmp(fname, "-")) {
    899 		Parse_File("(stdin)", stdin);
    900 		Var_Set("MAKEFILE", "", VAR_GLOBAL);
    901 	} else {
    902 		if ((stream = fopen(fname, "r")) != NULL)
    903 			goto found;
    904 		/* if we've chdir'd, rebuild the path name */
    905 		if (curdir != objdir && *fname != '/') {
    906 			size_t plen = strlen(curdir) + strlen(fname) + 2;
    907 			if (len < plen)
    908 				path = erealloc(path, len = 2 * plen);
    909 
    910 			(void)snprintf(path, len, "%s/%s", curdir, fname);
    911 			if ((stream = fopen(path, "r")) != NULL) {
    912 				fname = path;
    913 				goto found;
    914 			}
    915 		}
    916 		/* look in -I and system include directories. */
    917 		name = Dir_FindFile(fname, parseIncPath);
    918 		if (!name)
    919 			name = Dir_FindFile(fname, sysIncPath);
    920 		if (!name || !(stream = fopen(name, "r"))) {
    921 			free(path);
    922 			return(FALSE);
    923 		}
    924 		fname = name;
    925 		/*
    926 		 * set the MAKEFILE variable desired by System V fans -- the
    927 		 * placement of the setting here means it gets set to the last
    928 		 * makefile specified, as it is set by SysV make.
    929 		 */
    930 found:		Var_Set("MAKEFILE", fname, VAR_GLOBAL);
    931 		Parse_File(fname, stream);
    932 		(void)fclose(stream);
    933 	}
    934 	free(path);
    935 	return(TRUE);
    936 }
    937 
    938 /*-
    939  * Cmd_Exec --
    940  *	Execute the command in cmd, and return the output of that command
    941  *	in a string.
    942  *
    943  * Results:
    944  *	A string containing the output of the command, or the empty string
    945  *	If err is not NULL, it contains the reason for the command failure
    946  *
    947  * Side Effects:
    948  *	The string must be freed by the caller.
    949  */
    950 char *
    951 Cmd_Exec(cmd, err)
    952     char *cmd;
    953     char **err;
    954 {
    955     char	*args[4];   	/* Args for invoking the shell */
    956     int 	fds[2];	    	/* Pipe streams */
    957     int 	cpid;	    	/* Child PID */
    958     int 	pid;	    	/* PID from wait() */
    959     char	*res;		/* result */
    960     int		status;		/* command exit status */
    961     Buffer	buf;		/* buffer to store the result */
    962     char	*cp;
    963     int		cc;
    964 
    965 
    966     *err = NULL;
    967 
    968     /*
    969      * Set up arguments for shell
    970      */
    971     args[0] = "sh";
    972     args[1] = "-c";
    973     args[2] = cmd;
    974     args[3] = NULL;
    975 
    976     /*
    977      * Open a pipe for fetching its output
    978      */
    979     if (pipe(fds) == -1) {
    980 	*err = "Couldn't create pipe for \"%s\"";
    981 	goto bad;
    982     }
    983 
    984     /*
    985      * Fork
    986      */
    987     switch (cpid = vfork()) {
    988     case 0:
    989 	/*
    990 	 * Close input side of pipe
    991 	 */
    992 	(void) close(fds[0]);
    993 
    994 	/*
    995 	 * Duplicate the output stream to the shell's output, then
    996 	 * shut the extra thing down. Note we don't fetch the error
    997 	 * stream...why not? Why?
    998 	 */
    999 	(void) dup2(fds[1], 1);
   1000 	(void) close(fds[1]);
   1001 
   1002 	(void) execv("/bin/sh", args);
   1003 	_exit(1);
   1004 	/*NOTREACHED*/
   1005 
   1006     case -1:
   1007 	*err = "Couldn't exec \"%s\"";
   1008 	goto bad;
   1009 
   1010     default:
   1011 	/*
   1012 	 * No need for the writing half
   1013 	 */
   1014 	(void) close(fds[1]);
   1015 
   1016 	buf = Buf_Init (MAKE_BSIZE);
   1017 
   1018 	do {
   1019 	    char   result[BUFSIZ];
   1020 	    cc = read(fds[0], result, sizeof(result));
   1021 	    if (cc > 0)
   1022 		Buf_AddBytes(buf, cc, (Byte *) result);
   1023 	}
   1024 	while (cc > 0 || (cc == -1 && errno == EINTR));
   1025 
   1026 	/*
   1027 	 * Close the input side of the pipe.
   1028 	 */
   1029 	(void) close(fds[0]);
   1030 
   1031 	/*
   1032 	 * Wait for the process to exit.
   1033 	 */
   1034 	while(((pid = wait(&status)) != cpid) && (pid >= 0))
   1035 	    continue;
   1036 
   1037 	res = (char *)Buf_GetAll (buf, &cc);
   1038 	Buf_Destroy (buf, FALSE);
   1039 
   1040 	if (cc == 0)
   1041 	    *err = "Couldn't read shell's output for \"%s\"";
   1042 
   1043 	if (status)
   1044 	    *err = "\"%s\" returned non-zero status";
   1045 
   1046 	/*
   1047 	 * Null-terminate the result, convert newlines to spaces and
   1048 	 * install it in the variable.
   1049 	 */
   1050 	res[cc] = '\0';
   1051 	cp = &res[cc];
   1052 
   1053 	if (cc > 0 && *--cp == '\n') {
   1054 	    /*
   1055 	     * A final newline is just stripped
   1056 	     */
   1057 	    *cp-- = '\0';
   1058 	}
   1059 	while (cp >= res) {
   1060 	    if (*cp == '\n') {
   1061 		*cp = ' ';
   1062 	    }
   1063 	    cp--;
   1064 	}
   1065 	break;
   1066     }
   1067     return res;
   1068 bad:
   1069     res = emalloc(1);
   1070     *res = '\0';
   1071     return res;
   1072 }
   1073 
   1074 /*-
   1075  * Error --
   1076  *	Print an error message given its format.
   1077  *
   1078  * Results:
   1079  *	None.
   1080  *
   1081  * Side Effects:
   1082  *	The message is printed.
   1083  */
   1084 /* VARARGS */
   1085 void
   1086 #ifdef __STDC__
   1087 Error(char *fmt, ...)
   1088 #else
   1089 Error(va_alist)
   1090 	va_dcl
   1091 #endif
   1092 {
   1093 	va_list ap;
   1094 #ifdef __STDC__
   1095 	va_start(ap, fmt);
   1096 #else
   1097 	char *fmt;
   1098 
   1099 	va_start(ap);
   1100 	fmt = va_arg(ap, char *);
   1101 #endif
   1102 	fprintf(stderr, "%s: ", progname);
   1103 	(void)vfprintf(stderr, fmt, ap);
   1104 	va_end(ap);
   1105 	(void)fprintf(stderr, "\n");
   1106 	(void)fflush(stderr);
   1107 }
   1108 
   1109 /*-
   1110  * Fatal --
   1111  *	Produce a Fatal error message. If jobs are running, waits for them
   1112  *	to finish.
   1113  *
   1114  * Results:
   1115  *	None
   1116  *
   1117  * Side Effects:
   1118  *	The program exits
   1119  */
   1120 /* VARARGS */
   1121 void
   1122 #ifdef __STDC__
   1123 Fatal(char *fmt, ...)
   1124 #else
   1125 Fatal(va_alist)
   1126 	va_dcl
   1127 #endif
   1128 {
   1129 	va_list ap;
   1130 #ifdef __STDC__
   1131 	va_start(ap, fmt);
   1132 #else
   1133 	char *fmt;
   1134 
   1135 	va_start(ap);
   1136 	fmt = va_arg(ap, char *);
   1137 #endif
   1138 	if (jobsRunning)
   1139 		Job_Wait();
   1140 
   1141 	(void)vfprintf(stderr, fmt, ap);
   1142 	va_end(ap);
   1143 	(void)fprintf(stderr, "\n");
   1144 	(void)fflush(stderr);
   1145 
   1146 	if (DEBUG(GRAPH2))
   1147 		Targ_PrintGraph(2);
   1148 	exit(2);		/* Not 1 so -q can distinguish error */
   1149 }
   1150 
   1151 /*
   1152  * Punt --
   1153  *	Major exception once jobs are being created. Kills all jobs, prints
   1154  *	a message and exits.
   1155  *
   1156  * Results:
   1157  *	None
   1158  *
   1159  * Side Effects:
   1160  *	All children are killed indiscriminately and the program Lib_Exits
   1161  */
   1162 /* VARARGS */
   1163 void
   1164 #ifdef __STDC__
   1165 Punt(char *fmt, ...)
   1166 #else
   1167 Punt(va_alist)
   1168 	va_dcl
   1169 #endif
   1170 {
   1171 	va_list ap;
   1172 #ifdef __STDC__
   1173 	va_start(ap, fmt);
   1174 #else
   1175 	char *fmt;
   1176 
   1177 	va_start(ap);
   1178 	fmt = va_arg(ap, char *);
   1179 #endif
   1180 
   1181 	(void)fprintf(stderr, "make: ");
   1182 	(void)vfprintf(stderr, fmt, ap);
   1183 	va_end(ap);
   1184 	(void)fprintf(stderr, "\n");
   1185 	(void)fflush(stderr);
   1186 
   1187 	DieHorribly();
   1188 }
   1189 
   1190 /*-
   1191  * DieHorribly --
   1192  *	Exit without giving a message.
   1193  *
   1194  * Results:
   1195  *	None
   1196  *
   1197  * Side Effects:
   1198  *	A big one...
   1199  */
   1200 void
   1201 DieHorribly()
   1202 {
   1203 	if (jobsRunning)
   1204 		Job_AbortAll();
   1205 	if (DEBUG(GRAPH2))
   1206 		Targ_PrintGraph(2);
   1207 	exit(2);		/* Not 1, so -q can distinguish error */
   1208 }
   1209 
   1210 /*
   1211  * Finish --
   1212  *	Called when aborting due to errors in child shell to signal
   1213  *	abnormal exit.
   1214  *
   1215  * Results:
   1216  *	None
   1217  *
   1218  * Side Effects:
   1219  *	The program exits
   1220  */
   1221 void
   1222 Finish(errors)
   1223 	int errors;	/* number of errors encountered in Make_Make */
   1224 {
   1225 	Fatal("%d error%s", errors, errors == 1 ? "" : "s");
   1226 }
   1227 
   1228 /*
   1229  * emalloc --
   1230  *	malloc, but die on error.
   1231  */
   1232 void *
   1233 emalloc(len)
   1234 	size_t len;
   1235 {
   1236 	void *p;
   1237 
   1238 	if ((p = malloc(len)) == NULL)
   1239 		enomem();
   1240 	return(p);
   1241 }
   1242 
   1243 /*
   1244  * estrdup --
   1245  *	strdup, but die on error.
   1246  */
   1247 char *
   1248 estrdup(str)
   1249 	const char *str;
   1250 {
   1251 	char *p;
   1252 
   1253 	if ((p = strdup(str)) == NULL)
   1254 		enomem();
   1255 	return(p);
   1256 }
   1257 
   1258 /*
   1259  * erealloc --
   1260  *	realloc, but die on error.
   1261  */
   1262 void *
   1263 erealloc(ptr, size)
   1264 	void *ptr;
   1265 	size_t size;
   1266 {
   1267 	if ((ptr = realloc(ptr, size)) == NULL)
   1268 		enomem();
   1269 	return(ptr);
   1270 }
   1271 
   1272 /*
   1273  * enomem --
   1274  *	die when out of memory.
   1275  */
   1276 void
   1277 enomem()
   1278 {
   1279 	(void)fprintf(stderr, "make: %s.\n", strerror(errno));
   1280 	exit(2);
   1281 }
   1282 
   1283 /*
   1284  * enunlink --
   1285  *	Remove a file carefully, avoiding directories.
   1286  */
   1287 int
   1288 eunlink(file)
   1289 	const char *file;
   1290 {
   1291 	struct stat st;
   1292 
   1293 	if (lstat(file, &st) == -1)
   1294 		return -1;
   1295 
   1296 	if (S_ISDIR(st.st_mode)) {
   1297 		errno = EISDIR;
   1298 		return -1;
   1299 	}
   1300 	return unlink(file);
   1301 }
   1302 
   1303 /*
   1304  * usage --
   1305  *	exit with usage message
   1306  */
   1307 static void
   1308 usage()
   1309 {
   1310 	(void)fprintf(stderr,
   1311 "usage: make [-Beiknqrst] [-D variable] [-d flags] [-f makefile ]\n\
   1312             [-I directory] [-j max_jobs] [-m directory] [-V variable]\n\
   1313             [variable=value] [target ...]\n");
   1314 	exit(2);
   1315 }
   1316 
   1317 
   1318 int
   1319 PrintAddr(a, b)
   1320     ClientData a;
   1321     ClientData b;
   1322 {
   1323     printf("%lx ", (unsigned long) a);
   1324     return b ? 0 : 0;
   1325 }
   1326