Home | History | Annotate | Line # | Download | only in make
main.c revision 1.40
      1 /*	$NetBSD: main.c,v 1.40 1998/03/26 19:20:37 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.40 1998/03/26 19:20:37 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.40 1998/03/26 19:20:37 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(line, &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(MAKEFLAGS, "", VAR_GLOBAL);
    624 	Var_Set("MFLAGS", "", VAR_GLOBAL);
    625 	Var_Set("MACHINE", machine, VAR_GLOBAL);
    626 	Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
    627 
    628 	/*
    629 	 * First snag any flags out of the MAKE environment variable.
    630 	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
    631 	 * in a different format).
    632 	 */
    633 #ifdef POSIX
    634 	Main_ParseArgLine(getenv("MAKEFLAGS"));
    635 #else
    636 	Main_ParseArgLine(getenv("MAKE"));
    637 #endif
    638 
    639 	MainParseArgs(argc, argv);
    640 
    641 	/*
    642 	 * Initialize archive, target and suffix modules in preparation for
    643 	 * parsing the makefile(s)
    644 	 */
    645 	Arch_Init();
    646 	Targ_Init();
    647 	Suff_Init();
    648 
    649 	DEFAULT = NILGNODE;
    650 	(void)time(&now);
    651 
    652 	/*
    653 	 * Set up the .TARGETS variable to contain the list of targets to be
    654 	 * created. If none specified, make the variable empty -- the parser
    655 	 * will fill the thing in with the default or .MAIN target.
    656 	 */
    657 	if (!Lst_IsEmpty(create)) {
    658 		LstNode ln;
    659 
    660 		for (ln = Lst_First(create); ln != NILLNODE;
    661 		    ln = Lst_Succ(ln)) {
    662 			char *name = (char *)Lst_Datum(ln);
    663 
    664 			Var_Append(".TARGETS", name, VAR_GLOBAL);
    665 		}
    666 	} else
    667 		Var_Set(".TARGETS", "", VAR_GLOBAL);
    668 
    669 
    670 	/*
    671 	 * If no user-supplied system path was given (through the -m option)
    672 	 * add the directories from the DEFSYSPATH (more than one may be given
    673 	 * as dir1:...:dirn) to the system include path.
    674 	 */
    675 	if (!mkIncPath) {
    676 		for (start = syspath; *start != '\0'; start = cp) {
    677 			for (cp = start; *cp != '\0' && *cp != ':'; cp++)
    678 				continue;
    679 			if (*cp == '\0') {
    680 				(void) Dir_AddDir(sysIncPath, start);
    681 			} else {
    682 				*cp++ = '\0';
    683 				(void) Dir_AddDir(sysIncPath, start);
    684 			}
    685 		}
    686 	}
    687 
    688 	/*
    689 	 * Read in the built-in rules first, followed by the specified
    690 	 * makefile, if it was (makefile != (char *) NULL), or the default
    691 	 * Makefile and makefile, in that order, if it wasn't.
    692 	 */
    693 	if (!noBuiltins) {
    694 		LstNode ln;
    695 
    696 		sysMkPath = Lst_Init (FALSE);
    697 		Dir_Expand (_PATH_DEFSYSMK, sysIncPath, sysMkPath);
    698 		if (Lst_IsEmpty(sysMkPath))
    699 			Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
    700 		ln = Lst_Find(sysMkPath, (ClientData)NULL, ReadMakefile);
    701 		if (ln != NILLNODE)
    702 			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
    703 	}
    704 
    705 	if (!Lst_IsEmpty(makefiles)) {
    706 		LstNode ln;
    707 
    708 		ln = Lst_Find(makefiles, (ClientData)NULL, ReadMakefile);
    709 		if (ln != NILLNODE)
    710 			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
    711 	} else if (!ReadMakefile("makefile", NULL))
    712 		(void)ReadMakefile("Makefile", NULL);
    713 
    714 	(void)ReadMakefile(".depend", NULL);
    715 
    716 	Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
    717 	if (p1)
    718 	    free(p1);
    719 
    720 	/* Install all the flags into the MAKE envariable. */
    721 	if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
    722 #ifdef POSIX
    723 		setenv("MAKEFLAGS", p, 1);
    724 #else
    725 		setenv("MAKE", p, 1);
    726 #endif
    727 	if (p1)
    728 	    free(p1);
    729 
    730 	/*
    731 	 * For compatibility, look at the directories in the VPATH variable
    732 	 * and add them to the search path, if the variable is defined. The
    733 	 * variable's value is in the same format as the PATH envariable, i.e.
    734 	 * <directory>:<directory>:<directory>...
    735 	 */
    736 	if (Var_Exists("VPATH", VAR_CMD)) {
    737 		char *vpath, *path, *cp, savec;
    738 		/*
    739 		 * GCC stores string constants in read-only memory, but
    740 		 * Var_Subst will want to write this thing, so store it
    741 		 * in an array
    742 		 */
    743 		static char VPATH[] = "${VPATH}";
    744 
    745 		vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
    746 		path = vpath;
    747 		do {
    748 			/* skip to end of directory */
    749 			for (cp = path; *cp != ':' && *cp != '\0'; cp++)
    750 				continue;
    751 			/* Save terminator character so know when to stop */
    752 			savec = *cp;
    753 			*cp = '\0';
    754 			/* Add directory to search path */
    755 			(void) Dir_AddDir(dirSearchPath, path);
    756 			*cp = savec;
    757 			path = cp + 1;
    758 		} while (savec == ':');
    759 		(void)free((Address)vpath);
    760 	}
    761 
    762 	/*
    763 	 * Now that all search paths have been read for suffixes et al, it's
    764 	 * time to add the default search path to their lists...
    765 	 */
    766 	Suff_DoPaths();
    767 
    768 	/* print the initial graph, if the user requested it */
    769 	if (DEBUG(GRAPH1))
    770 		Targ_PrintGraph(1);
    771 
    772 	/* print the values of any variables requested by the user */
    773 	if (printVars) {
    774 		LstNode ln;
    775 
    776 		for (ln = Lst_First(variables); ln != NILLNODE;
    777 		    ln = Lst_Succ(ln)) {
    778 			char *value = Var_Value((char *)Lst_Datum(ln),
    779 					  VAR_GLOBAL, &p1);
    780 
    781 			printf("%s\n", value ? value : "");
    782 			if (p1)
    783 				free(p1);
    784 		}
    785 	}
    786 
    787 	/*
    788 	 * Have now read the entire graph and need to make a list of targets
    789 	 * to create. If none was given on the command line, we consult the
    790 	 * parsing module to find the main target(s) to create.
    791 	 */
    792 	if (Lst_IsEmpty(create))
    793 		targs = Parse_MainName();
    794 	else
    795 		targs = Targ_FindList(create, TARG_CREATE);
    796 
    797 	if (!compatMake && !printVars) {
    798 		/*
    799 		 * Initialize job module before traversing the graph, now that
    800 		 * any .BEGIN and .END targets have been read.  This is done
    801 		 * only if the -q flag wasn't given (to prevent the .BEGIN from
    802 		 * being executed should it exist).
    803 		 */
    804 		if (!queryFlag) {
    805 			if (maxLocal == -1)
    806 				maxLocal = maxJobs;
    807 			Job_Init(maxJobs, maxLocal);
    808 			jobsRunning = TRUE;
    809 		}
    810 
    811 		/* Traverse the graph, checking on all the targets */
    812 		outOfDate = Make_Run(targs);
    813 	} else if (!printVars) {
    814 		/*
    815 		 * Compat_Init will take care of creating all the targets as
    816 		 * well as initializing the module.
    817 		 */
    818 		Compat_Run(targs);
    819 	}
    820 
    821 	Lst_Destroy(targs, NOFREE);
    822 	Lst_Destroy(variables, NOFREE);
    823 	Lst_Destroy(makefiles, NOFREE);
    824 	Lst_Destroy(create, (void (*) __P((ClientData))) free);
    825 
    826 	/* print the graph now it's been processed if the user requested it */
    827 	if (DEBUG(GRAPH2))
    828 		Targ_PrintGraph(2);
    829 
    830 	Suff_End();
    831         Targ_End();
    832 	Arch_End();
    833 	Var_End();
    834 	Parse_End();
    835 	Dir_End();
    836 	Job_End();
    837 
    838 	if (queryFlag && outOfDate)
    839 		return(1);
    840 	else
    841 		return(0);
    842 }
    843 
    844 /*-
    845  * ReadMakefile  --
    846  *	Open and parse the given makefile.
    847  *
    848  * Results:
    849  *	TRUE if ok. FALSE if couldn't open file.
    850  *
    851  * Side Effects:
    852  *	lots
    853  */
    854 static Boolean
    855 ReadMakefile(p, q)
    856 	ClientData p, q;
    857 {
    858 	char *fname = p;		/* makefile to read */
    859 	extern Lst parseIncPath;
    860 	FILE *stream;
    861 	char *name, path[MAXPATHLEN + 1];
    862 
    863 	if (!strcmp(fname, "-")) {
    864 		Parse_File("(stdin)", stdin);
    865 		Var_Set("MAKEFILE", "", VAR_GLOBAL);
    866 	} else {
    867 		if ((stream = fopen(fname, "r")) != NULL)
    868 			goto found;
    869 		/* if we've chdir'd, rebuild the path name */
    870 		if (curdir != objdir && *fname != '/') {
    871 			(void)sprintf(path, "%s/%s", curdir, fname);
    872 			if ((stream = fopen(path, "r")) != NULL) {
    873 				fname = path;
    874 				goto found;
    875 			}
    876 		}
    877 		/* look in -I and system include directories. */
    878 		name = Dir_FindFile(fname, parseIncPath);
    879 		if (!name)
    880 			name = Dir_FindFile(fname, sysIncPath);
    881 		if (!name || !(stream = fopen(name, "r")))
    882 			return(FALSE);
    883 		fname = name;
    884 		/*
    885 		 * set the MAKEFILE variable desired by System V fans -- the
    886 		 * placement of the setting here means it gets set to the last
    887 		 * makefile specified, as it is set by SysV make.
    888 		 */
    889 found:		Var_Set("MAKEFILE", fname, VAR_GLOBAL);
    890 		Parse_File(fname, stream);
    891 		(void)fclose(stream);
    892 	}
    893 	return(TRUE);
    894 }
    895 
    896 /*-
    897  * Cmd_Exec --
    898  *	Execute the command in cmd, and return the output of that command
    899  *	in a string.
    900  *
    901  * Results:
    902  *	A string containing the output of the command, or the empty string
    903  *	If err is not NULL, it contains the reason for the command failure
    904  *
    905  * Side Effects:
    906  *	The string must be freed by the caller.
    907  */
    908 char *
    909 Cmd_Exec(cmd, err)
    910     char *cmd;
    911     char **err;
    912 {
    913     char	*args[4];   	/* Args for invoking the shell */
    914     int 	fds[2];	    	/* Pipe streams */
    915     int 	cpid;	    	/* Child PID */
    916     int 	pid;	    	/* PID from wait() */
    917     char	*res;		/* result */
    918     int		status;		/* command exit status */
    919     Buffer	buf;		/* buffer to store the result */
    920     char	*cp;
    921     int		cc;
    922 
    923 
    924     *err = NULL;
    925 
    926     /*
    927      * Set up arguments for shell
    928      */
    929     args[0] = "sh";
    930     args[1] = "-c";
    931     args[2] = cmd;
    932     args[3] = NULL;
    933 
    934     /*
    935      * Open a pipe for fetching its output
    936      */
    937     if (pipe(fds) == -1) {
    938 	*err = "Couldn't create pipe for \"%s\"";
    939 	goto bad;
    940     }
    941 
    942     /*
    943      * Fork
    944      */
    945     switch (cpid = vfork()) {
    946     case 0:
    947 	/*
    948 	 * Close input side of pipe
    949 	 */
    950 	(void) close(fds[0]);
    951 
    952 	/*
    953 	 * Duplicate the output stream to the shell's output, then
    954 	 * shut the extra thing down. Note we don't fetch the error
    955 	 * stream...why not? Why?
    956 	 */
    957 	(void) dup2(fds[1], 1);
    958 	(void) close(fds[1]);
    959 
    960 	(void) execv("/bin/sh", args);
    961 	_exit(1);
    962 	/*NOTREACHED*/
    963 
    964     case -1:
    965 	*err = "Couldn't exec \"%s\"";
    966 	goto bad;
    967 
    968     default:
    969 	/*
    970 	 * No need for the writing half
    971 	 */
    972 	(void) close(fds[1]);
    973 
    974 	buf = Buf_Init (MAKE_BSIZE);
    975 
    976 	do {
    977 	    char   result[BUFSIZ];
    978 	    cc = read(fds[0], result, sizeof(result));
    979 	    if (cc > 0)
    980 		Buf_AddBytes(buf, cc, (Byte *) result);
    981 	}
    982 	while (cc > 0 || (cc == -1 && errno == EINTR));
    983 
    984 	/*
    985 	 * Close the input side of the pipe.
    986 	 */
    987 	(void) close(fds[0]);
    988 
    989 	/*
    990 	 * Wait for the process to exit.
    991 	 */
    992 	while(((pid = wait(&status)) != cpid) && (pid >= 0))
    993 	    continue;
    994 
    995 	res = (char *)Buf_GetAll (buf, &cc);
    996 	Buf_Destroy (buf, FALSE);
    997 
    998 	if (cc == 0)
    999 	    *err = "Couldn't read shell's output for \"%s\"";
   1000 
   1001 	if (status)
   1002 	    *err = "\"%s\" returned non-zero status";
   1003 
   1004 	/*
   1005 	 * Null-terminate the result, convert newlines to spaces and
   1006 	 * install it in the variable.
   1007 	 */
   1008 	res[cc] = '\0';
   1009 	cp = &res[cc] - 1;
   1010 
   1011 	if (*cp == '\n') {
   1012 	    /*
   1013 	     * A final newline is just stripped
   1014 	     */
   1015 	    *cp-- = '\0';
   1016 	}
   1017 	while (cp >= res) {
   1018 	    if (*cp == '\n') {
   1019 		*cp = ' ';
   1020 	    }
   1021 	    cp--;
   1022 	}
   1023 	break;
   1024     }
   1025     return res;
   1026 bad:
   1027     res = emalloc(1);
   1028     *res = '\0';
   1029     return res;
   1030 }
   1031 
   1032 /*-
   1033  * Error --
   1034  *	Print an error message given its format.
   1035  *
   1036  * Results:
   1037  *	None.
   1038  *
   1039  * Side Effects:
   1040  *	The message is printed.
   1041  */
   1042 /* VARARGS */
   1043 void
   1044 #ifdef __STDC__
   1045 Error(char *fmt, ...)
   1046 #else
   1047 Error(va_alist)
   1048 	va_dcl
   1049 #endif
   1050 {
   1051 	va_list ap;
   1052 #ifdef __STDC__
   1053 	va_start(ap, fmt);
   1054 #else
   1055 	char *fmt;
   1056 
   1057 	va_start(ap);
   1058 	fmt = va_arg(ap, char *);
   1059 #endif
   1060 	(void)vfprintf(stderr, fmt, ap);
   1061 	va_end(ap);
   1062 	(void)fprintf(stderr, "\n");
   1063 	(void)fflush(stderr);
   1064 }
   1065 
   1066 /*-
   1067  * Fatal --
   1068  *	Produce a Fatal error message. If jobs are running, waits for them
   1069  *	to finish.
   1070  *
   1071  * Results:
   1072  *	None
   1073  *
   1074  * Side Effects:
   1075  *	The program exits
   1076  */
   1077 /* VARARGS */
   1078 void
   1079 #ifdef __STDC__
   1080 Fatal(char *fmt, ...)
   1081 #else
   1082 Fatal(va_alist)
   1083 	va_dcl
   1084 #endif
   1085 {
   1086 	va_list ap;
   1087 #ifdef __STDC__
   1088 	va_start(ap, fmt);
   1089 #else
   1090 	char *fmt;
   1091 
   1092 	va_start(ap);
   1093 	fmt = va_arg(ap, char *);
   1094 #endif
   1095 	if (jobsRunning)
   1096 		Job_Wait();
   1097 
   1098 	(void)vfprintf(stderr, fmt, ap);
   1099 	va_end(ap);
   1100 	(void)fprintf(stderr, "\n");
   1101 	(void)fflush(stderr);
   1102 
   1103 	if (DEBUG(GRAPH2))
   1104 		Targ_PrintGraph(2);
   1105 	exit(2);		/* Not 1 so -q can distinguish error */
   1106 }
   1107 
   1108 /*
   1109  * Punt --
   1110  *	Major exception once jobs are being created. Kills all jobs, prints
   1111  *	a message and exits.
   1112  *
   1113  * Results:
   1114  *	None
   1115  *
   1116  * Side Effects:
   1117  *	All children are killed indiscriminately and the program Lib_Exits
   1118  */
   1119 /* VARARGS */
   1120 void
   1121 #ifdef __STDC__
   1122 Punt(char *fmt, ...)
   1123 #else
   1124 Punt(va_alist)
   1125 	va_dcl
   1126 #endif
   1127 {
   1128 	va_list ap;
   1129 #ifdef __STDC__
   1130 	va_start(ap, fmt);
   1131 #else
   1132 	char *fmt;
   1133 
   1134 	va_start(ap);
   1135 	fmt = va_arg(ap, char *);
   1136 #endif
   1137 
   1138 	(void)fprintf(stderr, "make: ");
   1139 	(void)vfprintf(stderr, fmt, ap);
   1140 	va_end(ap);
   1141 	(void)fprintf(stderr, "\n");
   1142 	(void)fflush(stderr);
   1143 
   1144 	DieHorribly();
   1145 }
   1146 
   1147 /*-
   1148  * DieHorribly --
   1149  *	Exit without giving a message.
   1150  *
   1151  * Results:
   1152  *	None
   1153  *
   1154  * Side Effects:
   1155  *	A big one...
   1156  */
   1157 void
   1158 DieHorribly()
   1159 {
   1160 	if (jobsRunning)
   1161 		Job_AbortAll();
   1162 	if (DEBUG(GRAPH2))
   1163 		Targ_PrintGraph(2);
   1164 	exit(2);		/* Not 1, so -q can distinguish error */
   1165 }
   1166 
   1167 /*
   1168  * Finish --
   1169  *	Called when aborting due to errors in child shell to signal
   1170  *	abnormal exit.
   1171  *
   1172  * Results:
   1173  *	None
   1174  *
   1175  * Side Effects:
   1176  *	The program exits
   1177  */
   1178 void
   1179 Finish(errors)
   1180 	int errors;	/* number of errors encountered in Make_Make */
   1181 {
   1182 	Fatal("%d error%s", errors, errors == 1 ? "" : "s");
   1183 }
   1184 
   1185 /*
   1186  * emalloc --
   1187  *	malloc, but die on error.
   1188  */
   1189 void *
   1190 emalloc(len)
   1191 	size_t len;
   1192 {
   1193 	void *p;
   1194 
   1195 	if ((p = malloc(len)) == NULL)
   1196 		enomem();
   1197 	return(p);
   1198 }
   1199 
   1200 /*
   1201  * estrdup --
   1202  *	strdup, but die on error.
   1203  */
   1204 char *
   1205 estrdup(str)
   1206 	const char *str;
   1207 {
   1208 	char *p;
   1209 
   1210 	if ((p = strdup(str)) == NULL)
   1211 		enomem();
   1212 	return(p);
   1213 }
   1214 
   1215 /*
   1216  * erealloc --
   1217  *	realloc, but die on error.
   1218  */
   1219 void *
   1220 erealloc(ptr, size)
   1221 	void *ptr;
   1222 	size_t size;
   1223 {
   1224 	if ((ptr = realloc(ptr, size)) == NULL)
   1225 		enomem();
   1226 	return(ptr);
   1227 }
   1228 
   1229 /*
   1230  * enomem --
   1231  *	die when out of memory.
   1232  */
   1233 void
   1234 enomem()
   1235 {
   1236 	(void)fprintf(stderr, "make: %s.\n", strerror(errno));
   1237 	exit(2);
   1238 }
   1239 
   1240 /*
   1241  * enunlink --
   1242  *	Remove a file carefully, avoiding directories.
   1243  */
   1244 int
   1245 eunlink(file)
   1246 	const char *file;
   1247 {
   1248 	struct stat st;
   1249 
   1250 	if (lstat(file, &st) == -1)
   1251 		return -1;
   1252 
   1253 	if (S_ISDIR(st.st_mode)) {
   1254 		errno = EISDIR;
   1255 		return -1;
   1256 	}
   1257 	return unlink(file);
   1258 }
   1259 
   1260 /*
   1261  * usage --
   1262  *	exit with usage message
   1263  */
   1264 static void
   1265 usage()
   1266 {
   1267 	(void)fprintf(stderr,
   1268 "usage: make [-Beiknqrst] [-D variable] [-d flags] [-f makefile ]\n\
   1269             [-I directory] [-j max_jobs] [-m directory] [-V variable]\n\
   1270             [variable=value] [target ...]\n");
   1271 	exit(2);
   1272 }
   1273 
   1274 
   1275 int
   1276 PrintAddr(a, b)
   1277     ClientData a;
   1278     ClientData b;
   1279 {
   1280     printf("%lx ", (unsigned long) a);
   1281     return b ? 0 : 0;
   1282 }
   1283