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