Home | History | Annotate | Line # | Download | only in make
main.c revision 1.46
      1 /*	$NetBSD: main.c,v 1.46 1999/08/02 15:23:11 hubertf 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.46 1999/08/02 15:23:11 hubertf 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.46 1999/08/02 15:23:11 hubertf 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 
    151 /*-
    152  * MainParseArgs --
    153  *	Parse a given argument vector. Called from main() and from
    154  *	Main_ParseArgLine() when the .MAKEFLAGS target is used.
    155  *
    156  *	XXX: Deal with command line overriding .MAKEFLAGS in makefile
    157  *
    158  * Results:
    159  *	None
    160  *
    161  * Side Effects:
    162  *	Various global and local flags will be set depending on the flags
    163  *	given
    164  */
    165 static void
    166 MainParseArgs(argc, argv)
    167 	int argc;
    168 	char **argv;
    169 {
    170 	extern int optind;
    171 	extern char *optarg;
    172 	int c, rc;
    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 			rc = sscanf(optarg, "%d", &maxLocal);
    205 			if (rc < 1 || 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 			rc = sscanf(optarg, "%d", &maxJobs);
    290 			if (rc < 1 || 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 
    393 	if (line == NULL)
    394 		return;
    395 	for (; *line == ' '; ++line)
    396 		continue;
    397 	if (!*line)
    398 		return;
    399 
    400 	buf = emalloc(strlen(line) + strlen(argv0) + 2);
    401 	(void)sprintf(buf, "%s %s", argv0, line);
    402 	if (p1)
    403 		free(p1);
    404 
    405 	argv = brk_string(buf, &argc, TRUE, &args);
    406 	free(buf);
    407 	MainParseArgs(argc, argv);
    408 
    409 	free(args);
    410 	free(argv);
    411 }
    412 
    413 char *
    414 chdir_verify_path(path, obpath)
    415 	char *path;
    416 	char *obpath;
    417 {
    418 	struct stat sb;
    419 
    420 	if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
    421 		if (chdir(path)) {
    422 			(void)fprintf(stderr, "make warning: %s: %s.\n",
    423 				      path, strerror(errno));
    424 			return 0;
    425 		}
    426 		else {
    427 			if (path[0] != '/') {
    428 				(void) snprintf(obpath, MAXPATHLEN, "%s/%s",
    429 						curdir, path);
    430 				return obpath;
    431 			}
    432 			else
    433 				return path;
    434 		}
    435 	}
    436 
    437 	return 0;
    438 }
    439 
    440 
    441 /*-
    442  * main --
    443  *	The main function, for obvious reasons. Initializes variables
    444  *	and a few modules, then parses the arguments give it in the
    445  *	environment and on the command line. Reads the system makefile
    446  *	followed by either Makefile, makefile or the file given by the
    447  *	-f argument. Sets the .MAKEFLAGS PMake variable based on all the
    448  *	flags it has received by then uses either the Make or the Compat
    449  *	module to create the initial list of targets.
    450  *
    451  * Results:
    452  *	If -q was given, exits -1 if anything was out-of-date. Else it exits
    453  *	0.
    454  *
    455  * Side Effects:
    456  *	The program exits when done. Targets are created. etc. etc. etc.
    457  */
    458 int
    459 main(argc, argv)
    460 	int argc;
    461 	char **argv;
    462 {
    463 	Lst targs;	/* target nodes to create -- passed to Make_Init */
    464 	Boolean outOfDate = TRUE; 	/* FALSE if all targets up to date */
    465 	struct stat sb, sa;
    466 	char *p, *p1, *path, *pathp, *pwd;
    467 	char mdpath[MAXPATHLEN + 1];
    468 	char obpath[MAXPATHLEN + 1];
    469 	char cdpath[MAXPATHLEN + 1];
    470     	char *machine = getenv("MACHINE");
    471 	char *machine_arch = getenv("MACHINE_ARCH");
    472 	Lst sysMkPath;			/* Path of sys.mk */
    473 	char *cp = NULL, *start;
    474 					/* avoid faults on read-only strings */
    475 	static char syspath[] = _PATH_DEFSYSPATH;
    476 
    477 #ifdef RLIMIT_NOFILE
    478 	/*
    479 	 * get rid of resource limit on file descriptors
    480 	 */
    481 	{
    482 		struct rlimit rl;
    483 		if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
    484 		    rl.rlim_cur != rl.rlim_max) {
    485 			rl.rlim_cur = rl.rlim_max;
    486 			(void) setrlimit(RLIMIT_NOFILE, &rl);
    487 		}
    488 	}
    489 #endif
    490 	/*
    491 	 * Find where we are and take care of PWD for the automounter...
    492 	 * All this code is so that we know where we are when we start up
    493 	 * on a different machine with pmake.
    494 	 */
    495 	curdir = cdpath;
    496 	if (getcwd(curdir, MAXPATHLEN) == NULL) {
    497 		(void)fprintf(stderr, "make: %s.\n", strerror(errno));
    498 		exit(2);
    499 	}
    500 
    501 	if (stat(curdir, &sa) == -1) {
    502 	    (void)fprintf(stderr, "make: %s: %s.\n",
    503 			  curdir, strerror(errno));
    504 	    exit(2);
    505 	}
    506 
    507 	if ((pwd = getenv("PWD")) != NULL) {
    508 	    if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
    509 		sa.st_dev == sb.st_dev)
    510 		(void) strcpy(curdir, pwd);
    511 	}
    512 
    513 	/*
    514 	 * Get the name of this type of MACHINE from utsname
    515 	 * so we can share an executable for similar machines.
    516 	 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
    517 	 *
    518 	 * Note that both MACHINE and MACHINE_ARCH are decided at
    519 	 * run-time.
    520 	 */
    521 	if (!machine) {
    522 #ifndef MAKE_BOOTSTRAP
    523 	    struct utsname utsname;
    524 
    525 	    if (uname(&utsname) == -1) {
    526 		    perror("make: uname");
    527 		    exit(2);
    528 	    }
    529 	    machine = utsname.machine;
    530 #else
    531 	    machine = MACHINE;
    532 #endif
    533 	}
    534 
    535 	if (!machine_arch) {
    536 #ifndef MACHINE_ARCH
    537 #ifdef __ARCHITECTURE__
    538             machine_arch = __ARCHITECTURE__;
    539 #else
    540 	    machine_arch = "unknown";	/* XXX: no uname -p yet */
    541 #endif
    542 #else
    543 	    machine_arch = MACHINE_ARCH;
    544 #endif
    545 	}
    546 
    547 	/*
    548 	 * If the MAKEOBJDIR (or by default, the _PATH_OBJDIR) directory
    549 	 * exists, change into it and build there.  (If a .${MACHINE} suffix
    550 	 * exists, use that directory instead).
    551 	 * Otherwise check MAKEOBJDIRPREFIX`cwd` (or by default,
    552 	 * _PATH_OBJDIRPREFIX`cwd`) and build there if it exists.
    553 	 * If all fails, use the current directory to build.
    554 	 *
    555 	 * Once things are initted,
    556 	 * have to add the original directory to the search path,
    557 	 * and modify the paths for the Makefiles apropriately.  The
    558 	 * current directory is also placed as a variable for make scripts.
    559 	 */
    560 	if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
    561 		if (!(path = getenv("MAKEOBJDIR"))) {
    562 			path = _PATH_OBJDIR;
    563 			pathp = _PATH_OBJDIRPREFIX;
    564 			(void) snprintf(mdpath, MAXPATHLEN, "%s.%s",
    565 					path, machine);
    566 			if (!(objdir = chdir_verify_path(mdpath, obpath)))
    567 				if (!(objdir=chdir_verify_path(path, obpath))) {
    568 					(void) snprintf(mdpath, MAXPATHLEN,
    569 							"%s%s", pathp, curdir);
    570 					if (!(objdir=chdir_verify_path(mdpath,
    571 								       obpath)))
    572 						objdir = curdir;
    573 				}
    574 		}
    575 		else if (!(objdir = chdir_verify_path(path, obpath)))
    576 			objdir = curdir;
    577 	}
    578 	else {
    579 		(void) snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
    580 		if (!(objdir = chdir_verify_path(mdpath, obpath)))
    581 			objdir = curdir;
    582 	}
    583 
    584 	setenv("PWD", objdir, 1);
    585 
    586 	create = Lst_Init(FALSE);
    587 	makefiles = Lst_Init(FALSE);
    588 	printVars = FALSE;
    589 	variables = Lst_Init(FALSE);
    590 	beSilent = FALSE;		/* Print commands as executed */
    591 	ignoreErrors = FALSE;		/* Pay attention to non-zero returns */
    592 	noExecute = FALSE;		/* Execute all commands */
    593 	keepgoing = FALSE;		/* Stop on error */
    594 	allPrecious = FALSE;		/* Remove targets when interrupted */
    595 	queryFlag = FALSE;		/* This is not just a check-run */
    596 	noBuiltins = FALSE;		/* Read the built-in rules */
    597 	touchFlag = FALSE;		/* Actually update targets */
    598 	usePipes = TRUE;		/* Catch child output in pipes */
    599 	debug = 0;			/* No debug verbosity, please. */
    600 	jobsRunning = FALSE;
    601 
    602 	maxLocal = DEFMAXLOCAL;		/* Set default local max concurrency */
    603 #ifdef REMOTE
    604 	maxJobs = DEFMAXJOBS;		/* Set default max concurrency */
    605 #else
    606 	maxJobs = maxLocal;
    607 #endif
    608 	compatMake = FALSE;		/* No compat mode */
    609 
    610 
    611 	/*
    612 	 * Initialize the parsing, directory and variable modules to prepare
    613 	 * for the reading of inclusion paths and variable settings on the
    614 	 * command line
    615 	 */
    616 
    617 	/*
    618 	 * Initialize directory structures so -I flags can be processed
    619 	 * correctly, if we have a different objdir, then let the directory
    620 	 * know our curdir.
    621 	 */
    622 	Dir_Init(curdir != objdir ? curdir : NULL);
    623 	Parse_Init();		/* Need to initialize the paths of #include
    624 				 * directories */
    625 	Var_Init();		/* As well as the lists of variables for
    626 				 * parsing arguments */
    627 	Var_Set(".CURDIR", curdir, VAR_GLOBAL);
    628 	Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
    629 
    630 	/*
    631 	 * Initialize various variables.
    632 	 *	MAKE also gets this name, for compatibility
    633 	 *	.MAKEFLAGS gets set to the empty string just in case.
    634 	 *	MFLAGS also gets initialized empty, for compatibility.
    635 	 */
    636 	Var_Set("MAKE", argv[0], VAR_GLOBAL);
    637 	Var_Set(".MAKE", argv[0], VAR_GLOBAL);
    638 	Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
    639 	Var_Set("MFLAGS", "", VAR_GLOBAL);
    640 	Var_Set("MACHINE", machine, VAR_GLOBAL);
    641 	Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
    642 
    643 	/*
    644 	 * First snag any flags out of the MAKE environment variable.
    645 	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
    646 	 * in a different format).
    647 	 */
    648 #ifdef POSIX
    649 	Main_ParseArgLine(getenv("MAKEFLAGS"));
    650 #else
    651 	Main_ParseArgLine(getenv("MAKE"));
    652 #endif
    653 
    654 	MainParseArgs(argc, argv);
    655 
    656 	/*
    657 	 * Initialize archive, target and suffix modules in preparation for
    658 	 * parsing the makefile(s)
    659 	 */
    660 	Arch_Init();
    661 	Targ_Init();
    662 	Suff_Init();
    663 
    664 	DEFAULT = NILGNODE;
    665 	(void)time(&now);
    666 
    667 	/*
    668 	 * Set up the .TARGETS variable to contain the list of targets to be
    669 	 * created. If none specified, make the variable empty -- the parser
    670 	 * will fill the thing in with the default or .MAIN target.
    671 	 */
    672 	if (!Lst_IsEmpty(create)) {
    673 		LstNode ln;
    674 
    675 		for (ln = Lst_First(create); ln != NILLNODE;
    676 		    ln = Lst_Succ(ln)) {
    677 			char *name = (char *)Lst_Datum(ln);
    678 
    679 			Var_Append(".TARGETS", name, VAR_GLOBAL);
    680 		}
    681 	} else
    682 		Var_Set(".TARGETS", "", VAR_GLOBAL);
    683 
    684 
    685 	/*
    686 	 * If no user-supplied system path was given (through the -m option)
    687 	 * add the directories from the DEFSYSPATH (more than one may be given
    688 	 * as dir1:...:dirn) to the system include path.
    689 	 */
    690 	if (!mkIncPath) {
    691 		for (start = syspath; *start != '\0'; start = cp) {
    692 			for (cp = start; *cp != '\0' && *cp != ':'; cp++)
    693 				continue;
    694 			if (*cp == '\0') {
    695 				(void) Dir_AddDir(sysIncPath, start);
    696 			} else {
    697 				*cp++ = '\0';
    698 				(void) Dir_AddDir(sysIncPath, start);
    699 			}
    700 		}
    701 	}
    702 
    703 	/*
    704 	 * Read in the built-in rules first, followed by the specified
    705 	 * makefile, if it was (makefile != (char *) NULL), or the default
    706 	 * Makefile and makefile, in that order, if it wasn't.
    707 	 */
    708 	if (!noBuiltins) {
    709 		LstNode ln;
    710 
    711 		sysMkPath = Lst_Init (FALSE);
    712 		Dir_Expand (_PATH_DEFSYSMK, sysIncPath, sysMkPath);
    713 		if (Lst_IsEmpty(sysMkPath))
    714 			Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
    715 		ln = Lst_Find(sysMkPath, (ClientData)NULL, ReadMakefile);
    716 		if (ln != NILLNODE)
    717 			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
    718 	}
    719 
    720 	if (!Lst_IsEmpty(makefiles)) {
    721 		LstNode ln;
    722 
    723 		ln = Lst_Find(makefiles, (ClientData)NULL, ReadMakefile);
    724 		if (ln != NILLNODE)
    725 			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
    726 	} else if (!ReadMakefile("makefile", NULL))
    727 		(void)ReadMakefile("Makefile", NULL);
    728 
    729 	(void)ReadMakefile(".depend", NULL);
    730 
    731 	Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
    732 	if (p1)
    733 	    free(p1);
    734 
    735 	/* Install all the flags into the MAKE envariable. */
    736 	if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
    737 #ifdef POSIX
    738 		setenv("MAKEFLAGS", p, 1);
    739 #else
    740 		setenv("MAKE", p, 1);
    741 #endif
    742 	if (p1)
    743 	    free(p1);
    744 
    745 	/*
    746 	 * For compatibility, look at the directories in the VPATH variable
    747 	 * and add them to the search path, if the variable is defined. The
    748 	 * variable's value is in the same format as the PATH envariable, i.e.
    749 	 * <directory>:<directory>:<directory>...
    750 	 */
    751 	if (Var_Exists("VPATH", VAR_CMD)) {
    752 		char *vpath, *path, *cp, savec;
    753 		/*
    754 		 * GCC stores string constants in read-only memory, but
    755 		 * Var_Subst will want to write this thing, so store it
    756 		 * in an array
    757 		 */
    758 		static char VPATH[] = "${VPATH}";
    759 
    760 		vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
    761 		path = vpath;
    762 		do {
    763 			/* skip to end of directory */
    764 			for (cp = path; *cp != ':' && *cp != '\0'; cp++)
    765 				continue;
    766 			/* Save terminator character so know when to stop */
    767 			savec = *cp;
    768 			*cp = '\0';
    769 			/* Add directory to search path */
    770 			(void) Dir_AddDir(dirSearchPath, path);
    771 			*cp = savec;
    772 			path = cp + 1;
    773 		} while (savec == ':');
    774 		(void)free((Address)vpath);
    775 	}
    776 
    777 	/*
    778 	 * Now that all search paths have been read for suffixes et al, it's
    779 	 * time to add the default search path to their lists...
    780 	 */
    781 	Suff_DoPaths();
    782 
    783 	/* print the initial graph, if the user requested it */
    784 	if (DEBUG(GRAPH1))
    785 		Targ_PrintGraph(1);
    786 
    787 	/* print the values of any variables requested by the user */
    788 	if (printVars) {
    789 		LstNode ln;
    790 
    791 		for (ln = Lst_First(variables); ln != NILLNODE;
    792 		    ln = Lst_Succ(ln)) {
    793 			char *value = Var_Value((char *)Lst_Datum(ln),
    794 					  VAR_GLOBAL, &p1);
    795 
    796 			printf("%s\n", value ? value : "");
    797 			if (p1)
    798 				free(p1);
    799 		}
    800 	}
    801 
    802 	/*
    803 	 * Have now read the entire graph and need to make a list of targets
    804 	 * to create. If none was given on the command line, we consult the
    805 	 * parsing module to find the main target(s) to create.
    806 	 */
    807 	if (Lst_IsEmpty(create))
    808 		targs = Parse_MainName();
    809 	else
    810 		targs = Targ_FindList(create, TARG_CREATE);
    811 
    812 	if (!compatMake && !printVars) {
    813 		/*
    814 		 * Initialize job module before traversing the graph, now that
    815 		 * any .BEGIN and .END targets have been read.  This is done
    816 		 * only if the -q flag wasn't given (to prevent the .BEGIN from
    817 		 * being executed should it exist).
    818 		 */
    819 		if (!queryFlag) {
    820 			if (maxLocal == -1)
    821 				maxLocal = maxJobs;
    822 			Job_Init(maxJobs, maxLocal);
    823 			jobsRunning = TRUE;
    824 		}
    825 
    826 		/* Traverse the graph, checking on all the targets */
    827 		outOfDate = Make_Run(targs);
    828 	} else if (!printVars) {
    829 		/*
    830 		 * Compat_Init will take care of creating all the targets as
    831 		 * well as initializing the module.
    832 		 */
    833 		Compat_Run(targs);
    834 	}
    835 
    836 	Lst_Destroy(targs, NOFREE);
    837 	Lst_Destroy(variables, NOFREE);
    838 	Lst_Destroy(makefiles, NOFREE);
    839 	Lst_Destroy(create, (void (*) __P((ClientData))) free);
    840 
    841 	/* print the graph now it's been processed if the user requested it */
    842 	if (DEBUG(GRAPH2))
    843 		Targ_PrintGraph(2);
    844 
    845 	Suff_End();
    846         Targ_End();
    847 	Arch_End();
    848 	Var_End();
    849 	Parse_End();
    850 	Dir_End();
    851 	Job_End();
    852 
    853 	if (queryFlag && outOfDate)
    854 		return(1);
    855 	else
    856 		return(0);
    857 }
    858 
    859 /*-
    860  * ReadMakefile  --
    861  *	Open and parse the given makefile.
    862  *
    863  * Results:
    864  *	TRUE if ok. FALSE if couldn't open file.
    865  *
    866  * Side Effects:
    867  *	lots
    868  */
    869 static Boolean
    870 ReadMakefile(p, q)
    871 	ClientData p, q;
    872 {
    873 	char *fname = p;		/* makefile to read */
    874 	extern Lst parseIncPath;
    875 	FILE *stream;
    876 	char *name, path[MAXPATHLEN + 1];
    877 
    878 	if (!strcmp(fname, "-")) {
    879 		Parse_File("(stdin)", stdin);
    880 		Var_Set("MAKEFILE", "", VAR_GLOBAL);
    881 	} else {
    882 		if ((stream = fopen(fname, "r")) != NULL)
    883 			goto found;
    884 		/* if we've chdir'd, rebuild the path name */
    885 		if (curdir != objdir && *fname != '/') {
    886 			(void)sprintf(path, "%s/%s", curdir, fname);
    887 			if ((stream = fopen(path, "r")) != NULL) {
    888 				fname = path;
    889 				goto found;
    890 			}
    891 		}
    892 		/* look in -I and system include directories. */
    893 		name = Dir_FindFile(fname, parseIncPath);
    894 		if (!name)
    895 			name = Dir_FindFile(fname, sysIncPath);
    896 		if (!name || !(stream = fopen(name, "r")))
    897 			return(FALSE);
    898 		fname = name;
    899 		/*
    900 		 * set the MAKEFILE variable desired by System V fans -- the
    901 		 * placement of the setting here means it gets set to the last
    902 		 * makefile specified, as it is set by SysV make.
    903 		 */
    904 found:		Var_Set("MAKEFILE", fname, VAR_GLOBAL);
    905 		Parse_File(fname, stream);
    906 		(void)fclose(stream);
    907 	}
    908 	return(TRUE);
    909 }
    910 
    911 /*-
    912  * Cmd_Exec --
    913  *	Execute the command in cmd, and return the output of that command
    914  *	in a string.
    915  *
    916  * Results:
    917  *	A string containing the output of the command, or the empty string
    918  *	If err is not NULL, it contains the reason for the command failure
    919  *
    920  * Side Effects:
    921  *	The string must be freed by the caller.
    922  */
    923 char *
    924 Cmd_Exec(cmd, err)
    925     char *cmd;
    926     char **err;
    927 {
    928     char	*args[4];   	/* Args for invoking the shell */
    929     int 	fds[2];	    	/* Pipe streams */
    930     int 	cpid;	    	/* Child PID */
    931     int 	pid;	    	/* PID from wait() */
    932     char	*res;		/* result */
    933     int		status;		/* command exit status */
    934     Buffer	buf;		/* buffer to store the result */
    935     char	*cp;
    936     int		cc;
    937 
    938 
    939     *err = NULL;
    940 
    941     /*
    942      * Set up arguments for shell
    943      */
    944     args[0] = "sh";
    945     args[1] = "-c";
    946     args[2] = cmd;
    947     args[3] = NULL;
    948 
    949     /*
    950      * Open a pipe for fetching its output
    951      */
    952     if (pipe(fds) == -1) {
    953 	*err = "Couldn't create pipe for \"%s\"";
    954 	goto bad;
    955     }
    956 
    957     /*
    958      * Fork
    959      */
    960     switch (cpid = vfork()) {
    961     case 0:
    962 	/*
    963 	 * Close input side of pipe
    964 	 */
    965 	(void) close(fds[0]);
    966 
    967 	/*
    968 	 * Duplicate the output stream to the shell's output, then
    969 	 * shut the extra thing down. Note we don't fetch the error
    970 	 * stream...why not? Why?
    971 	 */
    972 	(void) dup2(fds[1], 1);
    973 	(void) close(fds[1]);
    974 
    975 	(void) execv("/bin/sh", args);
    976 	_exit(1);
    977 	/*NOTREACHED*/
    978 
    979     case -1:
    980 	*err = "Couldn't exec \"%s\"";
    981 	goto bad;
    982 
    983     default:
    984 	/*
    985 	 * No need for the writing half
    986 	 */
    987 	(void) close(fds[1]);
    988 
    989 	buf = Buf_Init (MAKE_BSIZE);
    990 
    991 	do {
    992 	    char   result[BUFSIZ];
    993 	    cc = read(fds[0], result, sizeof(result));
    994 	    if (cc > 0)
    995 		Buf_AddBytes(buf, cc, (Byte *) result);
    996 	}
    997 	while (cc > 0 || (cc == -1 && errno == EINTR));
    998 
    999 	/*
   1000 	 * Close the input side of the pipe.
   1001 	 */
   1002 	(void) close(fds[0]);
   1003 
   1004 	/*
   1005 	 * Wait for the process to exit.
   1006 	 */
   1007 	while(((pid = wait(&status)) != cpid) && (pid >= 0))
   1008 	    continue;
   1009 
   1010 	res = (char *)Buf_GetAll (buf, &cc);
   1011 	Buf_Destroy (buf, FALSE);
   1012 
   1013 	if (cc == 0)
   1014 	    *err = "Couldn't read shell's output for \"%s\"";
   1015 
   1016 	if (status)
   1017 	    *err = "\"%s\" returned non-zero status";
   1018 
   1019 	/*
   1020 	 * Null-terminate the result, convert newlines to spaces and
   1021 	 * install it in the variable.
   1022 	 */
   1023 	res[cc] = '\0';
   1024 	cp = &res[cc];
   1025 
   1026 	if (cc > 0 && *--cp == '\n') {
   1027 	    /*
   1028 	     * A final newline is just stripped
   1029 	     */
   1030 	    *cp-- = '\0';
   1031 	}
   1032 	while (cp >= res) {
   1033 	    if (*cp == '\n') {
   1034 		*cp = ' ';
   1035 	    }
   1036 	    cp--;
   1037 	}
   1038 	break;
   1039     }
   1040     return res;
   1041 bad:
   1042     res = emalloc(1);
   1043     *res = '\0';
   1044     return res;
   1045 }
   1046 
   1047 /*-
   1048  * Error --
   1049  *	Print an error message given its format.
   1050  *
   1051  * Results:
   1052  *	None.
   1053  *
   1054  * Side Effects:
   1055  *	The message is printed.
   1056  */
   1057 /* VARARGS */
   1058 void
   1059 #ifdef __STDC__
   1060 Error(char *fmt, ...)
   1061 #else
   1062 Error(va_alist)
   1063 	va_dcl
   1064 #endif
   1065 {
   1066 	va_list ap;
   1067 #ifdef __STDC__
   1068 	va_start(ap, fmt);
   1069 #else
   1070 	char *fmt;
   1071 
   1072 	va_start(ap);
   1073 	fmt = va_arg(ap, char *);
   1074 #endif
   1075 	(void)vfprintf(stderr, fmt, ap);
   1076 	va_end(ap);
   1077 	(void)fprintf(stderr, "\n");
   1078 	(void)fflush(stderr);
   1079 }
   1080 
   1081 /*-
   1082  * Fatal --
   1083  *	Produce a Fatal error message. If jobs are running, waits for them
   1084  *	to finish.
   1085  *
   1086  * Results:
   1087  *	None
   1088  *
   1089  * Side Effects:
   1090  *	The program exits
   1091  */
   1092 /* VARARGS */
   1093 void
   1094 #ifdef __STDC__
   1095 Fatal(char *fmt, ...)
   1096 #else
   1097 Fatal(va_alist)
   1098 	va_dcl
   1099 #endif
   1100 {
   1101 	va_list ap;
   1102 #ifdef __STDC__
   1103 	va_start(ap, fmt);
   1104 #else
   1105 	char *fmt;
   1106 
   1107 	va_start(ap);
   1108 	fmt = va_arg(ap, char *);
   1109 #endif
   1110 	if (jobsRunning)
   1111 		Job_Wait();
   1112 
   1113 	(void)vfprintf(stderr, fmt, ap);
   1114 	va_end(ap);
   1115 	(void)fprintf(stderr, "\n");
   1116 	(void)fflush(stderr);
   1117 
   1118 	if (DEBUG(GRAPH2))
   1119 		Targ_PrintGraph(2);
   1120 	exit(2);		/* Not 1 so -q can distinguish error */
   1121 }
   1122 
   1123 /*
   1124  * Punt --
   1125  *	Major exception once jobs are being created. Kills all jobs, prints
   1126  *	a message and exits.
   1127  *
   1128  * Results:
   1129  *	None
   1130  *
   1131  * Side Effects:
   1132  *	All children are killed indiscriminately and the program Lib_Exits
   1133  */
   1134 /* VARARGS */
   1135 void
   1136 #ifdef __STDC__
   1137 Punt(char *fmt, ...)
   1138 #else
   1139 Punt(va_alist)
   1140 	va_dcl
   1141 #endif
   1142 {
   1143 	va_list ap;
   1144 #ifdef __STDC__
   1145 	va_start(ap, fmt);
   1146 #else
   1147 	char *fmt;
   1148 
   1149 	va_start(ap);
   1150 	fmt = va_arg(ap, char *);
   1151 #endif
   1152 
   1153 	(void)fprintf(stderr, "make: ");
   1154 	(void)vfprintf(stderr, fmt, ap);
   1155 	va_end(ap);
   1156 	(void)fprintf(stderr, "\n");
   1157 	(void)fflush(stderr);
   1158 
   1159 	DieHorribly();
   1160 }
   1161 
   1162 /*-
   1163  * DieHorribly --
   1164  *	Exit without giving a message.
   1165  *
   1166  * Results:
   1167  *	None
   1168  *
   1169  * Side Effects:
   1170  *	A big one...
   1171  */
   1172 void
   1173 DieHorribly()
   1174 {
   1175 	if (jobsRunning)
   1176 		Job_AbortAll();
   1177 	if (DEBUG(GRAPH2))
   1178 		Targ_PrintGraph(2);
   1179 	exit(2);		/* Not 1, so -q can distinguish error */
   1180 }
   1181 
   1182 /*
   1183  * Finish --
   1184  *	Called when aborting due to errors in child shell to signal
   1185  *	abnormal exit.
   1186  *
   1187  * Results:
   1188  *	None
   1189  *
   1190  * Side Effects:
   1191  *	The program exits
   1192  */
   1193 void
   1194 Finish(errors)
   1195 	int errors;	/* number of errors encountered in Make_Make */
   1196 {
   1197 	Fatal("%d error%s", errors, errors == 1 ? "" : "s");
   1198 }
   1199 
   1200 /*
   1201  * emalloc --
   1202  *	malloc, but die on error.
   1203  */
   1204 void *
   1205 emalloc(len)
   1206 	size_t len;
   1207 {
   1208 	void *p;
   1209 
   1210 	if ((p = malloc(len)) == NULL)
   1211 		enomem();
   1212 	return(p);
   1213 }
   1214 
   1215 /*
   1216  * estrdup --
   1217  *	strdup, but die on error.
   1218  */
   1219 char *
   1220 estrdup(str)
   1221 	const char *str;
   1222 {
   1223 	char *p;
   1224 
   1225 	if ((p = strdup(str)) == NULL)
   1226 		enomem();
   1227 	return(p);
   1228 }
   1229 
   1230 /*
   1231  * erealloc --
   1232  *	realloc, but die on error.
   1233  */
   1234 void *
   1235 erealloc(ptr, size)
   1236 	void *ptr;
   1237 	size_t size;
   1238 {
   1239 	if ((ptr = realloc(ptr, size)) == NULL)
   1240 		enomem();
   1241 	return(ptr);
   1242 }
   1243 
   1244 /*
   1245  * enomem --
   1246  *	die when out of memory.
   1247  */
   1248 void
   1249 enomem()
   1250 {
   1251 	(void)fprintf(stderr, "make: %s.\n", strerror(errno));
   1252 	exit(2);
   1253 }
   1254 
   1255 /*
   1256  * enunlink --
   1257  *	Remove a file carefully, avoiding directories.
   1258  */
   1259 int
   1260 eunlink(file)
   1261 	const char *file;
   1262 {
   1263 	struct stat st;
   1264 
   1265 	if (lstat(file, &st) == -1)
   1266 		return -1;
   1267 
   1268 	if (S_ISDIR(st.st_mode)) {
   1269 		errno = EISDIR;
   1270 		return -1;
   1271 	}
   1272 	return unlink(file);
   1273 }
   1274 
   1275 /*
   1276  * usage --
   1277  *	exit with usage message
   1278  */
   1279 static void
   1280 usage()
   1281 {
   1282 	(void)fprintf(stderr,
   1283 "usage: make [-Beiknqrst] [-D variable] [-d flags] [-f makefile ]\n\
   1284             [-I directory] [-j max_jobs] [-m directory] [-V variable]\n\
   1285             [variable=value] [target ...]\n");
   1286 	exit(2);
   1287 }
   1288 
   1289 
   1290 int
   1291 PrintAddr(a, b)
   1292     ClientData a;
   1293     ClientData b;
   1294 {
   1295     printf("%lx ", (unsigned long) a);
   1296     return b ? 0 : 0;
   1297 }
   1298