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