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