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