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