Home | History | Annotate | Line # | Download | only in make
main.c revision 1.354
      1 /*	$NetBSD: main.c,v 1.354 2020/10/01 23:02:07 rillig 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 /*-
     72  * main.c --
     73  *	The main file for this entire program. Exit routines etc
     74  *	reside here.
     75  *
     76  * Utility functions defined in this file:
     77  *	Main_ParseArgLine	Takes a line of arguments, breaks them and
     78  *				treats them as if they were given when first
     79  *				invoked. Used by the parse module to implement
     80  *				the .MFLAGS target.
     81  *
     82  *	Error			Print a tagged error message. The global
     83  *				MAKE variable must have been defined. This
     84  *				takes a format string and optional arguments
     85  *				for it.
     86  *
     87  *	Fatal			Print an error message and exit. Also takes
     88  *				a format string and arguments for it.
     89  *
     90  *	Punt			Aborts all jobs and exits with a message. Also
     91  *				takes a format string and arguments for it.
     92  *
     93  *	Finish			Finish things up by printing the number of
     94  *				errors which occurred, as passed to it, and
     95  *				exiting.
     96  */
     97 
     98 #include <sys/types.h>
     99 #include <sys/time.h>
    100 #include <sys/param.h>
    101 #include <sys/resource.h>
    102 #include <sys/stat.h>
    103 #ifdef MAKE_NATIVE
    104 #include <sys/sysctl.h>
    105 #endif
    106 #include <sys/utsname.h>
    107 #include <sys/wait.h>
    108 
    109 #include <ctype.h>
    110 #include <errno.h>
    111 #include <signal.h>
    112 #include <stdarg.h>
    113 #include <stdio.h>
    114 #include <stdlib.h>
    115 #include <time.h>
    116 
    117 #include "make.h"
    118 #include "hash.h"
    119 #include "dir.h"
    120 #include "job.h"
    121 #include "pathnames.h"
    122 #include "trace.h"
    123 
    124 #ifdef USE_IOVEC
    125 #include <sys/uio.h>
    126 #endif
    127 
    128 /*	"@(#)main.c	8.3 (Berkeley) 3/19/94"	*/
    129 MAKE_RCSID("$NetBSD: main.c,v 1.354 2020/10/01 23:02:07 rillig Exp $");
    130 #if defined(MAKE_NATIVE) && !defined(lint)
    131 __COPYRIGHT("@(#) Copyright (c) 1988, 1989, 1990, 1993\
    132  The Regents of the University of California.  All rights reserved.");
    133 #endif
    134 
    135 #ifndef	DEFMAXLOCAL
    136 #define	DEFMAXLOCAL DEFMAXJOBS
    137 #endif
    138 
    139 StringList *		create;		/* Targets to be made */
    140 time_t			now;		/* Time at start of make */
    141 GNode			*DEFAULT;	/* .DEFAULT node */
    142 Boolean			allPrecious;	/* .PRECIOUS given on line by itself */
    143 Boolean			deleteOnError;	/* .DELETE_ON_ERROR: set */
    144 
    145 static Boolean		noBuiltins;	/* -r flag */
    146 static StringList *	makefiles;	/* ordered list of makefiles to read */
    147 static int		printVars;	/* -[vV] argument */
    148 #define COMPAT_VARS 1
    149 #define EXPAND_VARS 2
    150 static StringList *	variables;	/* list of variables to print
    151 					 * (for -v and -V) */
    152 int			maxJobs;	/* -j argument */
    153 static int		maxJobTokens;	/* -j argument */
    154 Boolean			compatMake;	/* -B argument */
    155 int			debug;		/* -d argument */
    156 Boolean			debugVflag;	/* -dV */
    157 Boolean			noExecute;	/* -n flag */
    158 Boolean			noRecursiveExecute;	/* -N flag */
    159 Boolean			keepgoing;	/* -k flag */
    160 Boolean			queryFlag;	/* -q flag */
    161 Boolean			touchFlag;	/* -t flag */
    162 Boolean			enterFlag;	/* -w flag */
    163 Boolean			enterFlagObj;	/* -w and objdir != srcdir */
    164 Boolean			ignoreErrors;	/* -i flag */
    165 Boolean			beSilent;	/* -s flag */
    166 Boolean			oldVars;	/* variable substitution style */
    167 Boolean			checkEnvFirst;	/* -e flag */
    168 Boolean			parseWarnFatal;	/* -W flag */
    169 static int jp_0 = -1, jp_1 = -1;	/* ends of parent job pipe */
    170 Boolean			varNoExportEnv;	/* -X flag */
    171 Boolean			doing_depend;	/* Set while reading .depend */
    172 static Boolean		jobsRunning;	/* TRUE if the jobs might be running */
    173 static const char *	tracefile;
    174 static int		ReadMakefile(const char *);
    175 static void		usage(void) MAKE_ATTR_DEAD;
    176 static void		purge_cached_realpaths(void);
    177 
    178 static Boolean		ignorePWD;	/* if we use -C, PWD is meaningless */
    179 static char objdir[MAXPATHLEN + 1];	/* where we chdir'ed to */
    180 char curdir[MAXPATHLEN + 1];		/* Startup directory */
    181 char *progname;				/* the program name */
    182 char *makeDependfile;
    183 pid_t myPid;
    184 int makelevel;
    185 
    186 FILE *debug_file;
    187 
    188 Boolean forceJobs = FALSE;
    189 
    190 extern SearchPath *parseIncPath;
    191 
    192 /*
    193  * For compatibility with the POSIX version of MAKEFLAGS that includes
    194  * all the options with out -, convert flags to -f -l -a -g -s.
    195  */
    196 static char *
    197 explode(const char *flags)
    198 {
    199     size_t len;
    200     char *nf, *st;
    201     const char *f;
    202 
    203     if (flags == NULL)
    204 	return NULL;
    205 
    206     for (f = flags; *f; f++)
    207 	if (!ch_isalpha(*f))
    208 	    break;
    209 
    210     if (*f)
    211 	return bmake_strdup(flags);
    212 
    213     len = strlen(flags);
    214     st = nf = bmake_malloc(len * 3 + 1);
    215     while (*flags) {
    216 	*nf++ = '-';
    217 	*nf++ = *flags++;
    218 	*nf++ = ' ';
    219     }
    220     *nf = '\0';
    221     return st;
    222 }
    223 
    224 static void
    225 parse_debug_option_F(const char *modules)
    226 {
    227     const char *mode;
    228     size_t len;
    229     char *fname;
    230 
    231     if (debug_file != stdout && debug_file != stderr)
    232 	fclose(debug_file);
    233 
    234     if (*modules == '+') {
    235 	modules++;
    236 	mode = "a";
    237     } else
    238 	mode = "w";
    239 
    240     if (strcmp(modules, "stdout") == 0) {
    241 	debug_file = stdout;
    242 	return;
    243     }
    244     if (strcmp(modules, "stderr") == 0) {
    245 	debug_file = stderr;
    246 	return;
    247     }
    248 
    249     len = strlen(modules);
    250     fname = bmake_malloc(len + 20);
    251     memcpy(fname, modules, len + 1);
    252 
    253     /* Let the filename be modified by the pid */
    254     if (strcmp(fname + len - 3, ".%d") == 0)
    255 	snprintf(fname + len - 2, 20, "%d", getpid());
    256 
    257     debug_file = fopen(fname, mode);
    258     if (!debug_file) {
    259 	fprintf(stderr, "Cannot open debug file %s\n",
    260 		fname);
    261 	usage();
    262     }
    263     free(fname);
    264 }
    265 
    266 static void
    267 parse_debug_options(const char *argvalue)
    268 {
    269 	const char *modules;
    270 
    271 	for (modules = argvalue; *modules; ++modules) {
    272 		switch (*modules) {
    273 		case 'A':
    274 			debug = ~(0|DEBUG_LINT);
    275 			break;
    276 		case 'a':
    277 			debug |= DEBUG_ARCH;
    278 			break;
    279 		case 'C':
    280 			debug |= DEBUG_CWD;
    281 			break;
    282 		case 'c':
    283 			debug |= DEBUG_COND;
    284 			break;
    285 		case 'd':
    286 			debug |= DEBUG_DIR;
    287 			break;
    288 		case 'e':
    289 			debug |= DEBUG_ERROR;
    290 			break;
    291 		case 'f':
    292 			debug |= DEBUG_FOR;
    293 			break;
    294 		case 'g':
    295 			if (modules[1] == '1') {
    296 				debug |= DEBUG_GRAPH1;
    297 				++modules;
    298 			}
    299 			else if (modules[1] == '2') {
    300 				debug |= DEBUG_GRAPH2;
    301 				++modules;
    302 			}
    303 			else if (modules[1] == '3') {
    304 				debug |= DEBUG_GRAPH3;
    305 				++modules;
    306 			}
    307 			break;
    308 		case 'h':
    309 			debug |= DEBUG_HASH;
    310 			break;
    311 		case 'j':
    312 			debug |= DEBUG_JOB;
    313 			break;
    314 		case 'L':
    315 			debug |= DEBUG_LINT;
    316 			break;
    317 		case 'l':
    318 			debug |= DEBUG_LOUD;
    319 			break;
    320 		case 'M':
    321 			debug |= DEBUG_META;
    322 			break;
    323 		case 'm':
    324 			debug |= DEBUG_MAKE;
    325 			break;
    326 		case 'n':
    327 			debug |= DEBUG_SCRIPT;
    328 			break;
    329 		case 'p':
    330 			debug |= DEBUG_PARSE;
    331 			break;
    332 		case 's':
    333 			debug |= DEBUG_SUFF;
    334 			break;
    335 		case 't':
    336 			debug |= DEBUG_TARG;
    337 			break;
    338 		case 'V':
    339 			debugVflag = TRUE;
    340 			break;
    341 		case 'v':
    342 			debug |= DEBUG_VAR;
    343 			break;
    344 		case 'x':
    345 			debug |= DEBUG_SHELL;
    346 			break;
    347 		case 'F':
    348 			parse_debug_option_F(modules + 1);
    349 			goto debug_setbuf;
    350 		default:
    351 			(void)fprintf(stderr,
    352 			    "%s: illegal argument to d option -- %c\n",
    353 			    progname, *modules);
    354 			usage();
    355 		}
    356 	}
    357 debug_setbuf:
    358 	/*
    359 	 * Make the debug_file unbuffered, and make
    360 	 * stdout line buffered (unless debugfile == stdout).
    361 	 */
    362 	setvbuf(debug_file, NULL, _IONBF, 0);
    363 	if (debug_file != stdout) {
    364 		setvbuf(stdout, NULL, _IOLBF, 0);
    365 	}
    366 }
    367 
    368 /*
    369  * does path contain any relative components
    370  */
    371 static Boolean
    372 is_relpath(const char *path)
    373 {
    374 	const char *cp;
    375 
    376 	if (path[0] != '/')
    377 		return TRUE;
    378 	cp = path;
    379 	while ((cp = strstr(cp, "/.")) != NULL) {
    380 		cp += 2;
    381 		if (cp[0] == '/' || cp[0] == '\0')
    382 			return TRUE;
    383 		else if (cp[0] == '.') {
    384 			if (cp[1] == '/' || cp[1] == '\0')
    385 				return TRUE;
    386 		}
    387 	}
    388 	return FALSE;
    389 }
    390 
    391 static Boolean
    392 MainParseArg(char c, char *argvalue)
    393 {
    394 	struct stat sa, sb;
    395 	char *p;
    396 	char found_path[MAXPATHLEN + 1];        /* for searching for sys.mk */
    397 
    398 	switch (c) {
    399 	case '\0':
    400 		break;
    401 	case 'B':
    402 		compatMake = TRUE;
    403 		Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
    404 		Var_Set(MAKE_MODE, "compat", VAR_GLOBAL);
    405 		break;
    406 	case 'C':
    407 		if (chdir(argvalue) == -1) {
    408 			(void)fprintf(stderr,
    409 				      "%s: chdir %s: %s\n",
    410 				      progname, argvalue,
    411 				      strerror(errno));
    412 			exit(1);
    413 		}
    414 		if (getcwd(curdir, MAXPATHLEN) == NULL) {
    415 			(void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
    416 			exit(2);
    417 		}
    418 		if (!is_relpath(argvalue) &&
    419 		    stat(argvalue, &sa) != -1 &&
    420 		    stat(curdir, &sb) != -1 &&
    421 		    sa.st_ino == sb.st_ino &&
    422 		    sa.st_dev == sb.st_dev)
    423 			strncpy(curdir, argvalue, MAXPATHLEN);
    424 		ignorePWD = TRUE;
    425 		break;
    426 	case 'D':
    427 		if (argvalue == NULL || argvalue[0] == 0) return FALSE;
    428 		Var_Set(argvalue, "1", VAR_GLOBAL);
    429 		Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
    430 		Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    431 		break;
    432 	case 'I':
    433 		if (argvalue == NULL) return FALSE;
    434 		Parse_AddIncludeDir(argvalue);
    435 		Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
    436 		Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    437 		break;
    438 	case 'J':
    439 		if (argvalue == NULL) return FALSE;
    440 		if (sscanf(argvalue, "%d,%d", &jp_0, &jp_1) != 2) {
    441 			(void)fprintf(stderr,
    442 				      "%s: internal error -- J option malformed (%s)\n",
    443 				      progname, argvalue);
    444 			usage();
    445 		}
    446 		if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
    447 		    (fcntl(jp_1, F_GETFD, 0) < 0)) {
    448 #if 0
    449 			(void)fprintf(stderr,
    450 			    "%s: ###### warning -- J descriptors were closed!\n",
    451 			    progname);
    452 			exit(2);
    453 #endif
    454 			jp_0 = -1;
    455 			jp_1 = -1;
    456 			compatMake = TRUE;
    457 		} else {
    458 			Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
    459 			Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    460 		}
    461 		break;
    462 	case 'N':
    463 		noExecute = TRUE;
    464 		noRecursiveExecute = TRUE;
    465 		Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
    466 		break;
    467 	case 'S':
    468 		keepgoing = FALSE;
    469 		Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
    470 		break;
    471 	case 'T':
    472 		if (argvalue == NULL) return FALSE;
    473 		tracefile = bmake_strdup(argvalue);
    474 		Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
    475 		Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    476 		break;
    477 	case 'V':
    478 	case 'v':
    479 		if (argvalue == NULL) return FALSE;
    480 		printVars = c == 'v' ? EXPAND_VARS : COMPAT_VARS;
    481 		Lst_Append(variables, bmake_strdup(argvalue));
    482 		Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
    483 		Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    484 		break;
    485 	case 'W':
    486 		parseWarnFatal = TRUE;
    487 		break;
    488 	case 'X':
    489 		varNoExportEnv = TRUE;
    490 		Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
    491 		break;
    492 	case 'd':
    493 		if (argvalue == NULL) return FALSE;
    494 		/* If '-d-opts' don't pass to children */
    495 		if (argvalue[0] == '-')
    496 			argvalue++;
    497 		else {
    498 			Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
    499 			Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    500 		}
    501 		parse_debug_options(argvalue);
    502 		break;
    503 	case 'e':
    504 		checkEnvFirst = TRUE;
    505 		Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
    506 		break;
    507 	case 'f':
    508 		if (argvalue == NULL) return FALSE;
    509 		Lst_Append(makefiles, bmake_strdup(argvalue));
    510 		break;
    511 	case 'i':
    512 		ignoreErrors = TRUE;
    513 		Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
    514 		break;
    515 	case 'j':
    516 		if (argvalue == NULL) return FALSE;
    517 		forceJobs = TRUE;
    518 		maxJobs = strtol(argvalue, &p, 0);
    519 		if (*p != '\0' || maxJobs < 1) {
    520 			(void)fprintf(stderr, "%s: illegal argument to -j -- must be positive integer!\n",
    521 			    progname);
    522 			exit(1);
    523 		}
    524 		Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
    525 		Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    526 		Var_Set(".MAKE.JOBS", argvalue, VAR_GLOBAL);
    527 		maxJobTokens = maxJobs;
    528 		break;
    529 	case 'k':
    530 		keepgoing = TRUE;
    531 		Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
    532 		break;
    533 	case 'm':
    534 		if (argvalue == NULL) return FALSE;
    535 		/* look for magic parent directory search string */
    536 		if (strncmp(".../", argvalue, 4) == 0) {
    537 			if (!Dir_FindHereOrAbove(curdir, argvalue + 4,
    538 			    found_path, sizeof(found_path)))
    539 				break;		/* nothing doing */
    540 			(void)Dir_AddDir(sysIncPath, found_path);
    541 		} else {
    542 			(void)Dir_AddDir(sysIncPath, argvalue);
    543 		}
    544 		Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
    545 		Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
    546 		break;
    547 	case 'n':
    548 		noExecute = TRUE;
    549 		Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
    550 		break;
    551 	case 'q':
    552 		queryFlag = TRUE;
    553 		/* Kind of nonsensical, wot? */
    554 		Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
    555 		break;
    556 	case 'r':
    557 		noBuiltins = TRUE;
    558 		Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
    559 		break;
    560 	case 's':
    561 		beSilent = TRUE;
    562 		Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
    563 		break;
    564 	case 't':
    565 		touchFlag = TRUE;
    566 		Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
    567 		break;
    568 	case 'w':
    569 		enterFlag = TRUE;
    570 		Var_Append(MAKEFLAGS, "-w", VAR_GLOBAL);
    571 		break;
    572 	default:
    573 	case '?':
    574 		usage();
    575 	}
    576 	return TRUE;
    577 }
    578 
    579 /* Parse the given arguments.  Called from main() and from
    580  * Main_ParseArgLine() when the .MAKEFLAGS target is used.
    581  *
    582  * The arguments must be treated as read-only and will be freed after the
    583  * call.
    584  *
    585  * XXX: Deal with command line overriding .MAKEFLAGS in makefile */
    586 static void
    587 MainParseArgs(int argc, char **argv)
    588 {
    589 	char c = '?';
    590 	int arginc;
    591 	char *argvalue;
    592 	const char *getopt_def;
    593 	char *optscan;
    594 	Boolean inOption, dashDash = FALSE;
    595 
    596 #define OPTFLAGS "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrstv:w"
    597 /* Can't actually use getopt(3) because rescanning is not portable */
    598 
    599 	getopt_def = OPTFLAGS;
    600 rearg:
    601 	inOption = FALSE;
    602 	optscan = NULL;
    603 	while(argc > 1) {
    604 		char *getopt_spec;
    605 		if(!inOption)
    606 			optscan = argv[1];
    607 		c = *optscan++;
    608 		arginc = 0;
    609 		if(inOption) {
    610 			if(c == '\0') {
    611 				++argv;
    612 				--argc;
    613 				inOption = FALSE;
    614 				continue;
    615 			}
    616 		} else {
    617 			if (c != '-' || dashDash)
    618 				break;
    619 			inOption = TRUE;
    620 			c = *optscan++;
    621 		}
    622 		/* '-' found at some earlier point */
    623 		getopt_spec = strchr(getopt_def, c);
    624 		if(c != '\0' && getopt_spec != NULL && getopt_spec[1] == ':') {
    625 			/* -<something> found, and <something> should have an arg */
    626 			inOption = FALSE;
    627 			arginc = 1;
    628 			argvalue = optscan;
    629 			if(*argvalue == '\0') {
    630 				if (argc < 3)
    631 					goto noarg;
    632 				argvalue = argv[2];
    633 				arginc = 2;
    634 			}
    635 		} else {
    636 			argvalue = NULL;
    637 		}
    638 		switch (c) {
    639 		case '\0':
    640 		    arginc = 1;
    641 		    inOption = FALSE;
    642 		    break;
    643 		case '-':
    644 		    dashDash = TRUE;
    645 		    break;
    646 		default:
    647 		    if (!MainParseArg(c, argvalue))
    648 		        goto noarg;
    649 		}
    650 		argv += arginc;
    651 		argc -= arginc;
    652 	}
    653 
    654 	oldVars = TRUE;
    655 
    656 	/*
    657 	 * See if the rest of the arguments are variable assignments and
    658 	 * perform them if so. Else take them to be targets and stuff them
    659 	 * on the end of the "create" list.
    660 	 */
    661 	for (; argc > 1; ++argv, --argc)
    662 		if (Parse_IsVar(argv[1])) {
    663 			Parse_DoVar(argv[1], VAR_CMD);
    664 		} else {
    665 			if (!*argv[1])
    666 				Punt("illegal (null) argument.");
    667 			if (*argv[1] == '-' && !dashDash)
    668 				goto rearg;
    669 			Lst_Append(create, bmake_strdup(argv[1]));
    670 		}
    671 
    672 	return;
    673 noarg:
    674 	(void)fprintf(stderr, "%s: option requires an argument -- %c\n",
    675 	    progname, c);
    676 	usage();
    677 }
    678 
    679 /*-
    680  * Main_ParseArgLine --
    681  *	Used by the parse module when a .MFLAGS or .MAKEFLAGS target
    682  *	is encountered and by main() when reading the .MAKEFLAGS envariable.
    683  *	Takes a line of arguments and breaks it into its
    684  *	component words and passes those words and the number of them to the
    685  *	MainParseArgs function.
    686  *	The line should have all its leading whitespace removed.
    687  *
    688  * Input:
    689  *	line		Line to fracture
    690  *
    691  * Results:
    692  *	None
    693  *
    694  * Side Effects:
    695  *	Only those that come from the various arguments.
    696  */
    697 void
    698 Main_ParseArgLine(const char *line)
    699 {
    700 	Words words;
    701 	char *p1;
    702 	const char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
    703 	char *buf;
    704 
    705 	if (line == NULL)
    706 		return;
    707 	for (; *line == ' '; ++line)
    708 		continue;
    709 	if (!*line)
    710 		return;
    711 
    712 	buf = str_concat3(argv0, " ", line);
    713 	free(p1);
    714 
    715 	words = Str_Words(buf, TRUE);
    716 	if (words.words == NULL) {
    717 		Error("Unterminated quoted string [%s]", buf);
    718 		free(buf);
    719 		return;
    720 	}
    721 	free(buf);
    722 	MainParseArgs((int)words.len, words.words);
    723 
    724 	Words_Free(words);
    725 }
    726 
    727 Boolean
    728 Main_SetObjdir(const char *fmt, ...)
    729 {
    730 	struct stat sb;
    731 	char *path;
    732 	char buf[MAXPATHLEN + 1];
    733 	char buf2[MAXPATHLEN + 1];
    734 	Boolean rc = FALSE;
    735 	va_list ap;
    736 
    737 	va_start(ap, fmt);
    738 	vsnprintf(path = buf, MAXPATHLEN, fmt, ap);
    739 	va_end(ap);
    740 
    741 	if (path[0] != '/') {
    742 		snprintf(buf2, MAXPATHLEN, "%s/%s", curdir, path);
    743 		path = buf2;
    744 	}
    745 
    746 	/* look for the directory and try to chdir there */
    747 	if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
    748 		if (chdir(path)) {
    749 			(void)fprintf(stderr, "make warning: %s: %s.\n",
    750 				      path, strerror(errno));
    751 		} else {
    752 			snprintf(objdir, sizeof objdir, "%s", path);
    753 			Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
    754 			setenv("PWD", objdir, 1);
    755 			Dir_InitDot();
    756 			purge_cached_realpaths();
    757 			rc = TRUE;
    758 			if (enterFlag && strcmp(objdir, curdir) != 0)
    759 				enterFlagObj = TRUE;
    760 		}
    761 	}
    762 
    763 	return rc;
    764 }
    765 
    766 static Boolean
    767 Main_SetVarObjdir(const char *var, const char *suffix)
    768 {
    769 	char *path_freeIt;
    770 	const char *path = Var_Value(var, VAR_CMD, &path_freeIt);
    771 	const char *xpath;
    772 	char *xpath_freeIt;
    773 
    774 	if (path == NULL || path[0] == '\0') {
    775 		bmake_free(path_freeIt);
    776 		return FALSE;
    777 	}
    778 
    779 	/* expand variable substitutions */
    780 	xpath = path;
    781 	xpath_freeIt = NULL;
    782 	if (strchr(path, '$') != 0) {
    783 		(void)Var_Subst(path, VAR_GLOBAL, VARE_WANTRES, &xpath_freeIt);
    784 		/* TODO: handle errors */
    785 		xpath = xpath_freeIt;
    786 	}
    787 
    788 	(void)Main_SetObjdir("%s%s", xpath, suffix);
    789 
    790 	bmake_free(xpath_freeIt);
    791 	bmake_free(path_freeIt);
    792 	return TRUE;
    793 }
    794 
    795 /* Read and parse the makefile.
    796  * Return TRUE if reading the makefile succeeded, for Lst_Find. */
    797 static Boolean
    798 ReadMakefileSucceeded(const void *fname, const void *unused)
    799 {
    800 	return ReadMakefile(fname) == 0;
    801 }
    802 
    803 /* Read and parse the makefile.
    804  * Return TRUE if reading the makefile failed, for Lst_Find. */
    805 static Boolean
    806 ReadMakefileFailed(const void *fname, const void *unused)
    807 {
    808 	return ReadMakefile(fname) != 0;
    809 }
    810 
    811 int
    812 str2Lst_Append(StringList *lp, char *str, const char *sep)
    813 {
    814     char *cp;
    815     int n;
    816 
    817     if (!sep)
    818 	sep = " \t";
    819 
    820     for (n = 0, cp = strtok(str, sep); cp; cp = strtok(NULL, sep)) {
    821 	Lst_Append(lp, cp);
    822 	n++;
    823     }
    824     return n;
    825 }
    826 
    827 #ifdef SIGINFO
    828 /*ARGSUSED*/
    829 static void
    830 siginfo(int signo MAKE_ATTR_UNUSED)
    831 {
    832 	char dir[MAXPATHLEN];
    833 	char str[2 * MAXPATHLEN];
    834 	int len;
    835 	if (getcwd(dir, sizeof(dir)) == NULL)
    836 		return;
    837 	len = snprintf(str, sizeof(str), "%s: Working in: %s\n", progname, dir);
    838 	if (len > 0)
    839 		(void)write(STDERR_FILENO, str, (size_t)len);
    840 }
    841 #endif
    842 
    843 /*
    844  * Allow makefiles some control over the mode we run in.
    845  */
    846 void
    847 MakeMode(const char *mode)
    848 {
    849     char *mode_freeIt = NULL;
    850 
    851     if (mode == NULL) {
    852 	(void)Var_Subst("${" MAKE_MODE ":tl}",
    853 		  VAR_GLOBAL, VARE_WANTRES, &mode_freeIt);
    854 	/* TODO: handle errors */
    855 	mode = mode_freeIt;
    856     }
    857 
    858     if (mode[0] != '\0') {
    859 	if (strstr(mode, "compat")) {
    860 	    compatMake = TRUE;
    861 	    forceJobs = FALSE;
    862 	}
    863 #if USE_META
    864 	if (strstr(mode, "meta"))
    865 	    meta_mode_init(mode);
    866 #endif
    867     }
    868 
    869     free(mode_freeIt);
    870 }
    871 
    872 static void
    873 doPrintVars(void)
    874 {
    875 	StringListNode *ln;
    876 	Boolean expandVars;
    877 
    878 	if (printVars == EXPAND_VARS)
    879 		expandVars = TRUE;
    880 	else if (debugVflag)
    881 		expandVars = FALSE;
    882 	else
    883 		expandVars = getBoolean(".MAKE.EXPAND_VARIABLES", FALSE);
    884 
    885 	for (ln = variables->first; ln != NULL; ln = ln->next) {
    886 		const char *var = ln->datum;
    887 		const char *value;
    888 		char *p1;
    889 
    890 		if (strchr(var, '$')) {
    891 			(void)Var_Subst(var, VAR_GLOBAL, VARE_WANTRES, &p1);
    892 			/* TODO: handle errors */
    893 			value = p1;
    894 		} else if (expandVars) {
    895 			char *expr = str_concat3("${", var, "}");
    896 			(void)Var_Subst(expr, VAR_GLOBAL, VARE_WANTRES, &p1);
    897 			/* TODO: handle errors */
    898 			value = p1;
    899 			free(expr);
    900 		} else {
    901 			value = Var_Value(var, VAR_GLOBAL, &p1);
    902 		}
    903 		printf("%s\n", value ? value : "");
    904 		bmake_free(p1);
    905 	}
    906 }
    907 
    908 static Boolean
    909 runTargets(void)
    910 {
    911 	GNodeList *targs; /* target nodes to create -- passed to Make_Init */
    912 	Boolean outOfDate;	/* FALSE if all targets up to date */
    913 
    914 	/*
    915 	 * Have now read the entire graph and need to make a list of
    916 	 * targets to create. If none was given on the command line,
    917 	 * we consult the parsing module to find the main target(s)
    918 	 * to create.
    919 	 */
    920 	if (Lst_IsEmpty(create))
    921 		targs = Parse_MainName();
    922 	else
    923 		targs = Targ_FindList(create);
    924 
    925 	if (!compatMake) {
    926 		/*
    927 		 * Initialize job module before traversing the graph
    928 		 * now that any .BEGIN and .END targets have been read.
    929 		 * This is done only if the -q flag wasn't given
    930 		 * (to prevent the .BEGIN from being executed should
    931 		 * it exist).
    932 		 */
    933 		if (!queryFlag) {
    934 			Job_Init();
    935 			jobsRunning = TRUE;
    936 		}
    937 
    938 		/* Traverse the graph, checking on all the targets */
    939 		outOfDate = Make_Run(targs);
    940 	} else {
    941 		/*
    942 		 * Compat_Init will take care of creating all the
    943 		 * targets as well as initializing the module.
    944 		 */
    945 		Compat_Run(targs);
    946 		outOfDate = FALSE;
    947 	}
    948 	Lst_Free(targs);
    949 	return outOfDate;
    950 }
    951 
    952 /*
    953  * Set up the .TARGETS variable to contain the list of targets to be
    954  * created. If none specified, make the variable empty -- the parser
    955  * will fill the thing in with the default or .MAIN target.
    956  */
    957 static void
    958 InitVarTargets(void)
    959 {
    960 	StringListNode *ln;
    961 
    962 	if (Lst_IsEmpty(create)) {
    963 		Var_Set(".TARGETS", "", VAR_GLOBAL);
    964 		return;
    965 	}
    966 
    967 	for (ln = create->first; ln != NULL; ln = ln->next) {
    968 		char *name = ln->datum;
    969 		Var_Append(".TARGETS", name, VAR_GLOBAL);
    970 	}
    971 }
    972 
    973 /*-
    974  * main --
    975  *	The main function, for obvious reasons. Initializes variables
    976  *	and a few modules, then parses the arguments give it in the
    977  *	environment and on the command line. Reads the system makefile
    978  *	followed by either Makefile, makefile or the file given by the
    979  *	-f argument. Sets the .MAKEFLAGS PMake variable based on all the
    980  *	flags it has received by then uses either the Make or the Compat
    981  *	module to create the initial list of targets.
    982  *
    983  * Results:
    984  *	If -q was given, exits -1 if anything was out-of-date. Else it exits
    985  *	0.
    986  *
    987  * Side Effects:
    988  *	The program exits when done. Targets are created. etc. etc. etc.
    989  */
    990 int
    991 main(int argc, char **argv)
    992 {
    993 	Boolean outOfDate;	/* FALSE if all targets up to date */
    994 	struct stat sb, sa;
    995 	char *p1, *path;
    996 	char mdpath[MAXPATHLEN];
    997 	const char *machine = getenv("MACHINE");
    998 	const char *machine_arch = getenv("MACHINE_ARCH");
    999 	char *syspath = getenv("MAKESYSPATH");
   1000 	StringList *sysMkPath;		/* Path of sys.mk */
   1001 	char *cp = NULL, *start;
   1002 					/* avoid faults on read-only strings */
   1003 	static char defsyspath[] = _PATH_DEFSYSPATH;
   1004 	char found_path[MAXPATHLEN + 1];	/* for searching for sys.mk */
   1005 	struct timeval rightnow;		/* to initialize random seed */
   1006 	struct utsname utsname;
   1007 
   1008 	/* default to writing debug to stderr */
   1009 	debug_file = stderr;
   1010 
   1011 #ifdef SIGINFO
   1012 	(void)bmake_signal(SIGINFO, siginfo);
   1013 #endif
   1014 	/*
   1015 	 * Set the seed to produce a different random sequence
   1016 	 * on each program execution.
   1017 	 */
   1018 	gettimeofday(&rightnow, NULL);
   1019 	srandom(rightnow.tv_sec + rightnow.tv_usec);
   1020 
   1021 	if ((progname = strrchr(argv[0], '/')) != NULL)
   1022 		progname++;
   1023 	else
   1024 		progname = argv[0];
   1025 #if defined(MAKE_NATIVE) || (defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE))
   1026 	/*
   1027 	 * get rid of resource limit on file descriptors
   1028 	 */
   1029 	{
   1030 		struct rlimit rl;
   1031 		if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
   1032 		    rl.rlim_cur != rl.rlim_max) {
   1033 			rl.rlim_cur = rl.rlim_max;
   1034 			(void)setrlimit(RLIMIT_NOFILE, &rl);
   1035 		}
   1036 	}
   1037 #endif
   1038 
   1039 	if (uname(&utsname) == -1) {
   1040 	    (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
   1041 		strerror(errno));
   1042 	    exit(2);
   1043 	}
   1044 
   1045 	/*
   1046 	 * Get the name of this type of MACHINE from utsname
   1047 	 * so we can share an executable for similar machines.
   1048 	 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
   1049 	 *
   1050 	 * Note that both MACHINE and MACHINE_ARCH are decided at
   1051 	 * run-time.
   1052 	 */
   1053 	if (!machine) {
   1054 #ifdef MAKE_NATIVE
   1055 	    machine = utsname.machine;
   1056 #else
   1057 #ifdef MAKE_MACHINE
   1058 	    machine = MAKE_MACHINE;
   1059 #else
   1060 	    machine = "unknown";
   1061 #endif
   1062 #endif
   1063 	}
   1064 
   1065 	if (!machine_arch) {
   1066 #ifdef MAKE_NATIVE
   1067 	    static char machine_arch_buf[sizeof(utsname.machine)];
   1068 	    const int mib[2] = { CTL_HW, HW_MACHINE_ARCH };
   1069 	    size_t len = sizeof(machine_arch_buf);
   1070 
   1071 	    if (sysctl(mib, __arraycount(mib), machine_arch_buf,
   1072 		    &len, NULL, 0) < 0) {
   1073 		(void)fprintf(stderr, "%s: sysctl failed (%s).\n", progname,
   1074 		    strerror(errno));
   1075 		exit(2);
   1076 	    }
   1077 
   1078 	    machine_arch = machine_arch_buf;
   1079 #else
   1080 #ifndef MACHINE_ARCH
   1081 #ifdef MAKE_MACHINE_ARCH
   1082 	    machine_arch = MAKE_MACHINE_ARCH;
   1083 #else
   1084 	    machine_arch = "unknown";
   1085 #endif
   1086 #else
   1087 	    machine_arch = MACHINE_ARCH;
   1088 #endif
   1089 #endif
   1090 	}
   1091 
   1092 	myPid = getpid();		/* remember this for vFork() */
   1093 
   1094 	/*
   1095 	 * Just in case MAKEOBJDIR wants us to do something tricky.
   1096 	 */
   1097 	Var_Init();		/* Initialize the lists of variables for
   1098 				 * parsing arguments */
   1099 	Var_Set(".MAKE.OS", utsname.sysname, VAR_GLOBAL);
   1100 	Var_Set("MACHINE", machine, VAR_GLOBAL);
   1101 	Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
   1102 #ifdef MAKE_VERSION
   1103 	Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
   1104 #endif
   1105 	Var_Set(".newline", "\n", VAR_GLOBAL); /* handy for :@ loops */
   1106 	/*
   1107 	 * This is the traditional preference for makefiles.
   1108 	 */
   1109 #ifndef MAKEFILE_PREFERENCE_LIST
   1110 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
   1111 #endif
   1112 	Var_Set(MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST,
   1113 		VAR_GLOBAL);
   1114 	Var_Set(MAKE_DEPENDFILE, ".depend", VAR_GLOBAL);
   1115 
   1116 	create = Lst_Init();
   1117 	makefiles = Lst_Init();
   1118 	printVars = 0;
   1119 	debugVflag = FALSE;
   1120 	variables = Lst_Init();
   1121 	beSilent = FALSE;		/* Print commands as executed */
   1122 	ignoreErrors = FALSE;		/* Pay attention to non-zero returns */
   1123 	noExecute = FALSE;		/* Execute all commands */
   1124 	noRecursiveExecute = FALSE;	/* Execute all .MAKE targets */
   1125 	keepgoing = FALSE;		/* Stop on error */
   1126 	allPrecious = FALSE;		/* Remove targets when interrupted */
   1127 	deleteOnError = FALSE;		/* Historical default behavior */
   1128 	queryFlag = FALSE;		/* This is not just a check-run */
   1129 	noBuiltins = FALSE;		/* Read the built-in rules */
   1130 	touchFlag = FALSE;		/* Actually update targets */
   1131 	debug = 0;			/* No debug verbosity, please. */
   1132 	jobsRunning = FALSE;
   1133 
   1134 	maxJobs = DEFMAXLOCAL;		/* Set default local max concurrency */
   1135 	maxJobTokens = maxJobs;
   1136 	compatMake = FALSE;		/* No compat mode */
   1137 	ignorePWD = FALSE;
   1138 
   1139 	/*
   1140 	 * Initialize the parsing, directory and variable modules to prepare
   1141 	 * for the reading of inclusion paths and variable settings on the
   1142 	 * command line
   1143 	 */
   1144 
   1145 	/*
   1146 	 * Initialize various variables.
   1147 	 *	MAKE also gets this name, for compatibility
   1148 	 *	.MAKEFLAGS gets set to the empty string just in case.
   1149 	 *	MFLAGS also gets initialized empty, for compatibility.
   1150 	 */
   1151 	Parse_Init();
   1152 	if (argv[0][0] == '/' || strchr(argv[0], '/') == NULL) {
   1153 	    /*
   1154 	     * Leave alone if it is an absolute path, or if it does
   1155 	     * not contain a '/' in which case we need to find it in
   1156 	     * the path, like execvp(3) and the shells do.
   1157 	     */
   1158 	    p1 = argv[0];
   1159 	} else {
   1160 	    /*
   1161 	     * A relative path, canonicalize it.
   1162 	     */
   1163 	    p1 = cached_realpath(argv[0], mdpath);
   1164 	    if (!p1 || *p1 != '/' || stat(p1, &sb) < 0) {
   1165 		p1 = argv[0];		/* realpath failed */
   1166 	    }
   1167 	}
   1168 	Var_Set("MAKE", p1, VAR_GLOBAL);
   1169 	Var_Set(".MAKE", p1, VAR_GLOBAL);
   1170 	Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
   1171 	Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL);
   1172 	Var_Set("MFLAGS", "", VAR_GLOBAL);
   1173 	Var_Set(".ALLTARGETS", "", VAR_GLOBAL);
   1174 	/* some makefiles need to know this */
   1175 	Var_Set(MAKE_LEVEL ".ENV", MAKE_LEVEL_ENV, VAR_CMD);
   1176 
   1177 	/*
   1178 	 * Set some other useful macros
   1179 	 */
   1180 	{
   1181 	    char tmp[64], *ep;
   1182 
   1183 	    makelevel = ((ep = getenv(MAKE_LEVEL_ENV)) && *ep) ? atoi(ep) : 0;
   1184 	    if (makelevel < 0)
   1185 		makelevel = 0;
   1186 	    snprintf(tmp, sizeof(tmp), "%d", makelevel);
   1187 	    Var_Set(MAKE_LEVEL, tmp, VAR_GLOBAL);
   1188 	    snprintf(tmp, sizeof(tmp), "%u", myPid);
   1189 	    Var_Set(".MAKE.PID", tmp, VAR_GLOBAL);
   1190 	    snprintf(tmp, sizeof(tmp), "%u", getppid());
   1191 	    Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL);
   1192 	}
   1193 	if (makelevel > 0) {
   1194 		char pn[1024];
   1195 		snprintf(pn, sizeof(pn), "%s[%d]", progname, makelevel);
   1196 		progname = bmake_strdup(pn);
   1197 	}
   1198 
   1199 #ifdef USE_META
   1200 	meta_init();
   1201 #endif
   1202 	Dir_Init();
   1203 
   1204 	/*
   1205 	 * First snag any flags out of the MAKE environment variable.
   1206 	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
   1207 	 * in a different format).
   1208 	 */
   1209 #ifdef POSIX
   1210 	p1 = explode(getenv("MAKEFLAGS"));
   1211 	Main_ParseArgLine(p1);
   1212 	free(p1);
   1213 #else
   1214 	Main_ParseArgLine(getenv("MAKE"));
   1215 #endif
   1216 
   1217 	/*
   1218 	 * Find where we are (now).
   1219 	 * We take care of PWD for the automounter below...
   1220 	 */
   1221 	if (getcwd(curdir, MAXPATHLEN) == NULL) {
   1222 		(void)fprintf(stderr, "%s: getcwd: %s.\n",
   1223 		    progname, strerror(errno));
   1224 		exit(2);
   1225 	}
   1226 
   1227 	MainParseArgs(argc, argv);
   1228 
   1229 	if (enterFlag)
   1230 		printf("%s: Entering directory `%s'\n", progname, curdir);
   1231 
   1232 	/*
   1233 	 * Verify that cwd is sane.
   1234 	 */
   1235 	if (stat(curdir, &sa) == -1) {
   1236 	    (void)fprintf(stderr, "%s: %s: %s.\n",
   1237 		 progname, curdir, strerror(errno));
   1238 	    exit(2);
   1239 	}
   1240 
   1241 	/*
   1242 	 * All this code is so that we know where we are when we start up
   1243 	 * on a different machine with pmake.
   1244 	 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
   1245 	 * since the value of curdir can vary depending on how we got
   1246 	 * here.  Ie sitting at a shell prompt (shell that provides $PWD)
   1247 	 * or via subdir.mk in which case its likely a shell which does
   1248 	 * not provide it.
   1249 	 * So, to stop it breaking this case only, we ignore PWD if
   1250 	 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
   1251 	 */
   1252 #ifndef NO_PWD_OVERRIDE
   1253 	if (!ignorePWD) {
   1254 		char *pwd, *ptmp1 = NULL, *ptmp2 = NULL;
   1255 
   1256 		if ((pwd = getenv("PWD")) != NULL &&
   1257 		    Var_Value("MAKEOBJDIRPREFIX", VAR_CMD, &ptmp1) == NULL) {
   1258 			const char *makeobjdir = Var_Value("MAKEOBJDIR",
   1259 			    VAR_CMD, &ptmp2);
   1260 
   1261 			if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
   1262 				if (stat(pwd, &sb) == 0 &&
   1263 				    sa.st_ino == sb.st_ino &&
   1264 				    sa.st_dev == sb.st_dev)
   1265 					(void)strncpy(curdir, pwd, MAXPATHLEN);
   1266 			}
   1267 		}
   1268 		bmake_free(ptmp1);
   1269 		bmake_free(ptmp2);
   1270 	}
   1271 #endif
   1272 	Var_Set(".CURDIR", curdir, VAR_GLOBAL);
   1273 
   1274 	/*
   1275 	 * Find the .OBJDIR.  If MAKEOBJDIRPREFIX, or failing that,
   1276 	 * MAKEOBJDIR is set in the environment, try only that value
   1277 	 * and fall back to .CURDIR if it does not exist.
   1278 	 *
   1279 	 * Otherwise, try _PATH_OBJDIR.MACHINE-MACHINE_ARCH, _PATH_OBJDIR.MACHINE,
   1280 	 * and * finally _PATH_OBJDIRPREFIX`pwd`, in that order.  If none
   1281 	 * of these paths exist, just use .CURDIR.
   1282 	 */
   1283 	Dir_InitDir(curdir);
   1284 	(void)Main_SetObjdir("%s", curdir);
   1285 
   1286 	if (!Main_SetVarObjdir("MAKEOBJDIRPREFIX", curdir) &&
   1287 	    !Main_SetVarObjdir("MAKEOBJDIR", "") &&
   1288 	    !Main_SetObjdir("%s.%s-%s", _PATH_OBJDIR, machine, machine_arch) &&
   1289 	    !Main_SetObjdir("%s.%s", _PATH_OBJDIR, machine) &&
   1290 	    !Main_SetObjdir("%s", _PATH_OBJDIR))
   1291 		(void)Main_SetObjdir("%s%s", _PATH_OBJDIRPREFIX, curdir);
   1292 
   1293 	/*
   1294 	 * Initialize archive, target and suffix modules in preparation for
   1295 	 * parsing the makefile(s)
   1296 	 */
   1297 	Arch_Init();
   1298 	Targ_Init();
   1299 	Suff_Init();
   1300 	Trace_Init(tracefile);
   1301 
   1302 	DEFAULT = NULL;
   1303 	(void)time(&now);
   1304 
   1305 	Trace_Log(MAKESTART, NULL);
   1306 
   1307 	InitVarTargets();
   1308 
   1309 	/*
   1310 	 * If no user-supplied system path was given (through the -m option)
   1311 	 * add the directories from the DEFSYSPATH (more than one may be given
   1312 	 * as dir1:...:dirn) to the system include path.
   1313 	 */
   1314 	/* XXX: mismatch: the -m option sets sysIncPath, not syspath */
   1315 	if (syspath == NULL || syspath[0] == '\0')
   1316 		syspath = defsyspath;
   1317 	else
   1318 		syspath = bmake_strdup(syspath);
   1319 
   1320 	for (start = syspath; *start != '\0'; start = cp) {
   1321 		for (cp = start; *cp != '\0' && *cp != ':'; cp++)
   1322 			continue;
   1323 		if (*cp == ':') {
   1324 			*cp++ = '\0';
   1325 		}
   1326 		/* look for magic parent directory search string */
   1327 		if (strncmp(".../", start, 4) != 0) {
   1328 			(void)Dir_AddDir(defIncPath, start);
   1329 		} else {
   1330 			if (Dir_FindHereOrAbove(curdir, start+4,
   1331 			    found_path, sizeof(found_path))) {
   1332 				(void)Dir_AddDir(defIncPath, found_path);
   1333 			}
   1334 		}
   1335 	}
   1336 	if (syspath != defsyspath)
   1337 		free(syspath);
   1338 
   1339 	/*
   1340 	 * Read in the built-in rules first, followed by the specified
   1341 	 * makefiles, or the default makefile and Makefile, in that order,
   1342 	 * if no makefiles were given on the command line.
   1343 	 */
   1344 	if (!noBuiltins) {
   1345 		StringListNode *ln;
   1346 
   1347 		sysMkPath = Lst_Init();
   1348 		Dir_Expand(_PATH_DEFSYSMK,
   1349 			   Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
   1350 			   sysMkPath);
   1351 		if (Lst_IsEmpty(sysMkPath))
   1352 			Fatal("%s: no system rules (%s).", progname,
   1353 			    _PATH_DEFSYSMK);
   1354 		ln = Lst_Find(sysMkPath, ReadMakefileSucceeded, NULL);
   1355 		if (ln == NULL)
   1356 			Fatal("%s: cannot open %s.", progname,
   1357 			    (char *)LstNode_Datum(Lst_First(sysMkPath)));
   1358 	}
   1359 
   1360 	if (!Lst_IsEmpty(makefiles)) {
   1361 		StringListNode *ln;
   1362 
   1363 		ln = Lst_Find(makefiles, ReadMakefileFailed, NULL);
   1364 		if (ln != NULL)
   1365 			Fatal("%s: cannot open %s.", progname,
   1366 			    (char *)LstNode_Datum(ln));
   1367 	} else {
   1368 		(void)Var_Subst("${" MAKEFILE_PREFERENCE "}",
   1369 		    VAR_CMD, VARE_WANTRES, &p1);
   1370 		/* TODO: handle errors */
   1371 		(void)str2Lst_Append(makefiles, p1, NULL);
   1372 		(void)Lst_Find(makefiles, ReadMakefileSucceeded, NULL);
   1373 		free(p1);
   1374 	}
   1375 
   1376 	/* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
   1377 	if (!noBuiltins || !printVars) {
   1378 	    (void)Var_Subst("${.MAKE.DEPENDFILE:T}",
   1379 		VAR_CMD, VARE_WANTRES, &makeDependfile);
   1380 	    /* TODO: handle errors */
   1381 	    doing_depend = TRUE;
   1382 	    (void)ReadMakefile(makeDependfile);
   1383 	    doing_depend = FALSE;
   1384 	}
   1385 
   1386 	if (enterFlagObj)
   1387 		printf("%s: Entering directory `%s'\n", progname, objdir);
   1388 
   1389 	MakeMode(NULL);
   1390 
   1391 	Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
   1392 	bmake_free(p1);
   1393 
   1394 	if (!forceJobs && !compatMake &&
   1395 	    Var_Exists(".MAKE.JOBS", VAR_GLOBAL)) {
   1396 	    char *value;
   1397 	    int n;
   1398 
   1399 	    (void)Var_Subst("${.MAKE.JOBS}", VAR_GLOBAL, VARE_WANTRES, &value);
   1400 	    /* TODO: handle errors */
   1401 	    n = strtol(value, NULL, 0);
   1402 	    if (n < 1) {
   1403 		(void)fprintf(stderr, "%s: illegal value for .MAKE.JOBS -- must be positive integer!\n",
   1404 		    progname);
   1405 		exit(1);
   1406 	    }
   1407 	    if (n != maxJobs) {
   1408 		Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
   1409 		Var_Append(MAKEFLAGS, value, VAR_GLOBAL);
   1410 	    }
   1411 	    maxJobs = n;
   1412 	    maxJobTokens = maxJobs;
   1413 	    forceJobs = TRUE;
   1414 	    free(value);
   1415 	}
   1416 
   1417 	/*
   1418 	 * Be compatible if user did not specify -j and did not explicitly
   1419 	 * turned compatibility on
   1420 	 */
   1421 	if (!compatMake && !forceJobs) {
   1422 	    compatMake = TRUE;
   1423 	}
   1424 
   1425 	if (!compatMake)
   1426 	    Job_ServerStart(maxJobTokens, jp_0, jp_1);
   1427 	DEBUG5(JOB, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
   1428 	       jp_0, jp_1, maxJobs, maxJobTokens, compatMake ? 1 : 0);
   1429 
   1430 	if (!printVars)
   1431 	    Main_ExportMAKEFLAGS(TRUE);	/* initial export */
   1432 
   1433 
   1434 	/*
   1435 	 * For compatibility, look at the directories in the VPATH variable
   1436 	 * and add them to the search path, if the variable is defined. The
   1437 	 * variable's value is in the same format as the PATH envariable, i.e.
   1438 	 * <directory>:<directory>:<directory>...
   1439 	 */
   1440 	if (Var_Exists("VPATH", VAR_CMD)) {
   1441 		char *vpath, savec;
   1442 		/*
   1443 		 * GCC stores string constants in read-only memory, but
   1444 		 * Var_Subst will want to write this thing, so store it
   1445 		 * in an array
   1446 		 */
   1447 		static char VPATH[] = "${VPATH}";
   1448 
   1449 		(void)Var_Subst(VPATH, VAR_CMD, VARE_WANTRES, &vpath);
   1450 		/* TODO: handle errors */
   1451 		path = vpath;
   1452 		do {
   1453 			/* skip to end of directory */
   1454 			for (cp = path; *cp != ':' && *cp != '\0'; cp++)
   1455 				continue;
   1456 			/* Save terminator character so know when to stop */
   1457 			savec = *cp;
   1458 			*cp = '\0';
   1459 			/* Add directory to search path */
   1460 			(void)Dir_AddDir(dirSearchPath, path);
   1461 			*cp = savec;
   1462 			path = cp + 1;
   1463 		} while (savec == ':');
   1464 		free(vpath);
   1465 	}
   1466 
   1467 	/*
   1468 	 * Now that all search paths have been read for suffixes et al, it's
   1469 	 * time to add the default search path to their lists...
   1470 	 */
   1471 	Suff_DoPaths();
   1472 
   1473 	/*
   1474 	 * Propagate attributes through :: dependency lists.
   1475 	 */
   1476 	Targ_Propagate();
   1477 
   1478 	/* print the initial graph, if the user requested it */
   1479 	if (DEBUG(GRAPH1))
   1480 		Targ_PrintGraph(1);
   1481 
   1482 	/* print the values of any variables requested by the user */
   1483 	if (printVars) {
   1484 		doPrintVars();
   1485 		outOfDate = FALSE;
   1486 	} else {
   1487 		outOfDate = runTargets();
   1488 	}
   1489 
   1490 #ifdef CLEANUP
   1491 	Lst_Free(variables);
   1492 	Lst_Free(makefiles);
   1493 	Lst_Destroy(create, free);
   1494 #endif
   1495 
   1496 	/* print the graph now it's been processed if the user requested it */
   1497 	if (DEBUG(GRAPH2))
   1498 		Targ_PrintGraph(2);
   1499 
   1500 	Trace_Log(MAKEEND, 0);
   1501 
   1502 	if (enterFlagObj)
   1503 		printf("%s: Leaving directory `%s'\n", progname, objdir);
   1504 	if (enterFlag)
   1505 		printf("%s: Leaving directory `%s'\n", progname, curdir);
   1506 
   1507 #ifdef USE_META
   1508 	meta_finish();
   1509 #endif
   1510 	Suff_End();
   1511 	Targ_End();
   1512 	Arch_End();
   1513 	Var_End();
   1514 	Parse_End();
   1515 	Dir_End();
   1516 	Job_End();
   1517 	Trace_End();
   1518 
   1519 	return outOfDate ? 1 : 0;
   1520 }
   1521 
   1522 /* Open and parse the given makefile, with all its side effects.
   1523  *
   1524  * Results:
   1525  *	0 if ok. -1 if couldn't open file.
   1526  */
   1527 static int
   1528 ReadMakefile(const char *fname)
   1529 {
   1530 	int fd;
   1531 	char *name, *path = NULL;
   1532 
   1533 	if (!strcmp(fname, "-")) {
   1534 		Parse_File(NULL /*stdin*/, -1);
   1535 		Var_Set("MAKEFILE", "", VAR_INTERNAL);
   1536 	} else {
   1537 		/* if we've chdir'd, rebuild the path name */
   1538 		if (strcmp(curdir, objdir) && *fname != '/') {
   1539 			path = str_concat3(curdir, "/", fname);
   1540 			fd = open(path, O_RDONLY);
   1541 			if (fd != -1) {
   1542 				fname = path;
   1543 				goto found;
   1544 			}
   1545 			free(path);
   1546 
   1547 			/* If curdir failed, try objdir (ala .depend) */
   1548 			path = str_concat3(objdir, "/", fname);
   1549 			fd = open(path, O_RDONLY);
   1550 			if (fd != -1) {
   1551 				fname = path;
   1552 				goto found;
   1553 			}
   1554 		} else {
   1555 			fd = open(fname, O_RDONLY);
   1556 			if (fd != -1)
   1557 				goto found;
   1558 		}
   1559 		/* look in -I and system include directories. */
   1560 		name = Dir_FindFile(fname, parseIncPath);
   1561 		if (!name)
   1562 			name = Dir_FindFile(fname,
   1563 				Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
   1564 		if (!name || (fd = open(name, O_RDONLY)) == -1) {
   1565 			free(name);
   1566 			free(path);
   1567 			return -1;
   1568 		}
   1569 		fname = name;
   1570 		/*
   1571 		 * set the MAKEFILE variable desired by System V fans -- the
   1572 		 * placement of the setting here means it gets set to the last
   1573 		 * makefile specified, as it is set by SysV make.
   1574 		 */
   1575 found:
   1576 		if (!doing_depend)
   1577 			Var_Set("MAKEFILE", fname, VAR_INTERNAL);
   1578 		Parse_File(fname, fd);
   1579 	}
   1580 	free(path);
   1581 	return 0;
   1582 }
   1583 
   1584 
   1585 
   1586 /*-
   1587  * Cmd_Exec --
   1588  *	Execute the command in cmd, and return the output of that command
   1589  *	in a string.  In the output, newlines are replaced with spaces.
   1590  *
   1591  * Results:
   1592  *	A string containing the output of the command, or the empty string.
   1593  *	*errfmt returns a format string describing the command failure,
   1594  *	if any, using a single %s conversion specification.
   1595  *
   1596  * Side Effects:
   1597  *	The string must be freed by the caller.
   1598  */
   1599 char *
   1600 Cmd_Exec(const char *cmd, const char **errfmt)
   1601 {
   1602     const char	*args[4];	/* Args for invoking the shell */
   1603     int		fds[2];		/* Pipe streams */
   1604     int		cpid;		/* Child PID */
   1605     int		pid;		/* PID from wait() */
   1606     int		status;		/* command exit status */
   1607     Buffer	buf;		/* buffer to store the result */
   1608     ssize_t	bytes_read;
   1609     char	*res;		/* result */
   1610     size_t	res_len;
   1611     char	*cp;
   1612     int		savederr;	/* saved errno */
   1613 
   1614     *errfmt = NULL;
   1615 
   1616     if (!shellName)
   1617 	Shell_Init();
   1618     /*
   1619      * Set up arguments for shell
   1620      */
   1621     args[0] = shellName;
   1622     args[1] = "-c";
   1623     args[2] = cmd;
   1624     args[3] = NULL;
   1625 
   1626     /*
   1627      * Open a pipe for fetching its output
   1628      */
   1629     if (pipe(fds) == -1) {
   1630 	*errfmt = "Couldn't create pipe for \"%s\"";
   1631 	goto bad;
   1632     }
   1633 
   1634     /*
   1635      * Fork
   1636      */
   1637     switch (cpid = vFork()) {
   1638     case 0:
   1639 	/*
   1640 	 * Close input side of pipe
   1641 	 */
   1642 	(void)close(fds[0]);
   1643 
   1644 	/*
   1645 	 * Duplicate the output stream to the shell's output, then
   1646 	 * shut the extra thing down. Note we don't fetch the error
   1647 	 * stream...why not? Why?
   1648 	 */
   1649 	(void)dup2(fds[1], 1);
   1650 	(void)close(fds[1]);
   1651 
   1652 	Var_ExportVars();
   1653 
   1654 	(void)execv(shellPath, UNCONST(args));
   1655 	_exit(1);
   1656 	/*NOTREACHED*/
   1657 
   1658     case -1:
   1659 	*errfmt = "Couldn't exec \"%s\"";
   1660 	goto bad;
   1661 
   1662     default:
   1663 	/*
   1664 	 * No need for the writing half
   1665 	 */
   1666 	(void)close(fds[1]);
   1667 
   1668 	savederr = 0;
   1669 	Buf_Init(&buf, 0);
   1670 
   1671 	do {
   1672 	    char   result[BUFSIZ];
   1673 	    bytes_read = read(fds[0], result, sizeof(result));
   1674 	    if (bytes_read > 0)
   1675 		Buf_AddBytes(&buf, result, (size_t)bytes_read);
   1676 	}
   1677 	while (bytes_read > 0 || (bytes_read == -1 && errno == EINTR));
   1678 	if (bytes_read == -1)
   1679 	    savederr = errno;
   1680 
   1681 	/*
   1682 	 * Close the input side of the pipe.
   1683 	 */
   1684 	(void)close(fds[0]);
   1685 
   1686 	/*
   1687 	 * Wait for the process to exit.
   1688 	 */
   1689 	while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) {
   1690 	    JobReapChild(pid, status, FALSE);
   1691 	    continue;
   1692 	}
   1693 	res_len = Buf_Len(&buf);
   1694 	res = Buf_Destroy(&buf, FALSE);
   1695 
   1696 	if (savederr != 0)
   1697 	    *errfmt = "Couldn't read shell's output for \"%s\"";
   1698 
   1699 	if (WIFSIGNALED(status))
   1700 	    *errfmt = "\"%s\" exited on a signal";
   1701 	else if (WEXITSTATUS(status) != 0)
   1702 	    *errfmt = "\"%s\" returned non-zero status";
   1703 
   1704 	/* Convert newlines to spaces.  A final newline is just stripped */
   1705 	if (res_len > 0 && res[res_len - 1] == '\n')
   1706 	    res[res_len - 1] = '\0';
   1707 	for (cp = res; *cp != '\0'; cp++)
   1708 	    if (*cp == '\n')
   1709 		*cp = ' ';
   1710 	break;
   1711     }
   1712     return res;
   1713 bad:
   1714     return bmake_strdup("");
   1715 }
   1716 
   1717 /*-
   1718  * Error --
   1719  *	Print an error message given its format.
   1720  *
   1721  * Results:
   1722  *	None.
   1723  *
   1724  * Side Effects:
   1725  *	The message is printed.
   1726  */
   1727 void
   1728 Error(const char *fmt, ...)
   1729 {
   1730 	va_list ap;
   1731 	FILE *err_file;
   1732 
   1733 	err_file = debug_file;
   1734 	if (err_file == stdout)
   1735 		err_file = stderr;
   1736 	(void)fflush(stdout);
   1737 	for (;;) {
   1738 		va_start(ap, fmt);
   1739 		fprintf(err_file, "%s: ", progname);
   1740 		(void)vfprintf(err_file, fmt, ap);
   1741 		va_end(ap);
   1742 		(void)fprintf(err_file, "\n");
   1743 		(void)fflush(err_file);
   1744 		if (err_file == stderr)
   1745 			break;
   1746 		err_file = stderr;
   1747 	}
   1748 }
   1749 
   1750 /* Produce a Fatal error message, then exit immediately.
   1751  *
   1752  * If jobs are running, waits for them to finish. */
   1753 void
   1754 Fatal(const char *fmt, ...)
   1755 {
   1756 	va_list ap;
   1757 
   1758 	va_start(ap, fmt);
   1759 	if (jobsRunning)
   1760 		Job_Wait();
   1761 
   1762 	(void)fflush(stdout);
   1763 	(void)vfprintf(stderr, fmt, ap);
   1764 	va_end(ap);
   1765 	(void)fprintf(stderr, "\n");
   1766 	(void)fflush(stderr);
   1767 
   1768 	PrintOnError(NULL, NULL);
   1769 
   1770 	if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
   1771 		Targ_PrintGraph(2);
   1772 	Trace_Log(MAKEERROR, 0);
   1773 	exit(2);		/* Not 1 so -q can distinguish error */
   1774 }
   1775 
   1776 /*
   1777  * Punt --
   1778  *	Major exception once jobs are being created. Kills all jobs, prints
   1779  *	a message and exits.
   1780  *
   1781  * Results:
   1782  *	None
   1783  *
   1784  * Side Effects:
   1785  *	All children are killed indiscriminately and the program Lib_Exits
   1786  */
   1787 void
   1788 Punt(const char *fmt, ...)
   1789 {
   1790 	va_list ap;
   1791 
   1792 	va_start(ap, fmt);
   1793 	(void)fflush(stdout);
   1794 	(void)fprintf(stderr, "%s: ", progname);
   1795 	(void)vfprintf(stderr, fmt, ap);
   1796 	va_end(ap);
   1797 	(void)fprintf(stderr, "\n");
   1798 	(void)fflush(stderr);
   1799 
   1800 	PrintOnError(NULL, NULL);
   1801 
   1802 	DieHorribly();
   1803 }
   1804 
   1805 /*-
   1806  * DieHorribly --
   1807  *	Exit without giving a message.
   1808  *
   1809  * Results:
   1810  *	None
   1811  *
   1812  * Side Effects:
   1813  *	A big one...
   1814  */
   1815 void
   1816 DieHorribly(void)
   1817 {
   1818 	if (jobsRunning)
   1819 		Job_AbortAll();
   1820 	if (DEBUG(GRAPH2))
   1821 		Targ_PrintGraph(2);
   1822 	Trace_Log(MAKEERROR, 0);
   1823 	exit(2);		/* Not 1, so -q can distinguish error */
   1824 }
   1825 
   1826 /*
   1827  * Finish --
   1828  *	Called when aborting due to errors in child shell to signal
   1829  *	abnormal exit.
   1830  *
   1831  * Results:
   1832  *	None
   1833  *
   1834  * Side Effects:
   1835  *	The program exits
   1836  */
   1837 void
   1838 Finish(int errors)
   1839 			/* number of errors encountered in Make_Make */
   1840 {
   1841 	if (dieQuietly(NULL, -1))
   1842 		exit(2);
   1843 	Fatal("%d error%s", errors, errors == 1 ? "" : "s");
   1844 }
   1845 
   1846 /*
   1847  * eunlink --
   1848  *	Remove a file carefully, avoiding directories.
   1849  */
   1850 int
   1851 eunlink(const char *file)
   1852 {
   1853 	struct stat st;
   1854 
   1855 	if (lstat(file, &st) == -1)
   1856 		return -1;
   1857 
   1858 	if (S_ISDIR(st.st_mode)) {
   1859 		errno = EISDIR;
   1860 		return -1;
   1861 	}
   1862 	return unlink(file);
   1863 }
   1864 
   1865 /*
   1866  * execError --
   1867  *	Print why exec failed, avoiding stdio.
   1868  */
   1869 void
   1870 execError(const char *af, const char *av)
   1871 {
   1872 #ifdef USE_IOVEC
   1873 	int i = 0;
   1874 	struct iovec iov[8];
   1875 #define IOADD(s) \
   1876 	(void)(iov[i].iov_base = UNCONST(s), \
   1877 	    iov[i].iov_len = strlen(iov[i].iov_base), \
   1878 	    i++)
   1879 #else
   1880 #define	IOADD(void)write(2, s, strlen(s))
   1881 #endif
   1882 
   1883 	IOADD(progname);
   1884 	IOADD(": ");
   1885 	IOADD(af);
   1886 	IOADD("(");
   1887 	IOADD(av);
   1888 	IOADD(") failed (");
   1889 	IOADD(strerror(errno));
   1890 	IOADD(")\n");
   1891 
   1892 #ifdef USE_IOVEC
   1893 	while (writev(2, iov, 8) == -1 && errno == EAGAIN)
   1894 	    continue;
   1895 #endif
   1896 }
   1897 
   1898 /*
   1899  * usage --
   1900  *	exit with usage message
   1901  */
   1902 static void
   1903 usage(void)
   1904 {
   1905 	char *p;
   1906 	if ((p = strchr(progname, '[')) != NULL)
   1907 		*p = '\0';
   1908 
   1909 	(void)fprintf(stderr,
   1910 "usage: %s [-BeikNnqrstWwX] \n"
   1911 "            [-C directory] [-D variable] [-d flags] [-f makefile]\n"
   1912 "            [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n"
   1913 "            [-V variable] [-v variable] [variable=value] [target ...]\n",
   1914 	    progname);
   1915 	exit(2);
   1916 }
   1917 
   1918 /*
   1919  * realpath(3) can get expensive, cache results...
   1920  */
   1921 static GNode *cached_realpaths = NULL;
   1922 
   1923 static GNode *
   1924 get_cached_realpaths(void)
   1925 {
   1926 
   1927     if (!cached_realpaths) {
   1928 	cached_realpaths = Targ_NewGN("Realpath");
   1929 #ifndef DEBUG_REALPATH_CACHE
   1930 	cached_realpaths->flags = INTERNAL;
   1931 #endif
   1932     }
   1933 
   1934     return cached_realpaths;
   1935 }
   1936 
   1937 /* purge any relative paths */
   1938 static void
   1939 purge_cached_realpaths(void)
   1940 {
   1941     GNode *cache = get_cached_realpaths();
   1942     Hash_Entry *he, *nhe;
   1943     Hash_Search hs;
   1944 
   1945     he = Hash_EnumFirst(&cache->context, &hs);
   1946     while (he) {
   1947 	nhe = Hash_EnumNext(&hs);
   1948 	if (he->name[0] != '/') {
   1949 	    if (DEBUG(DIR))
   1950 		fprintf(stderr, "cached_realpath: purging %s\n", he->name);
   1951 	    Hash_DeleteEntry(&cache->context, he);
   1952 	}
   1953 	he = nhe;
   1954     }
   1955 }
   1956 
   1957 char *
   1958 cached_realpath(const char *pathname, char *resolved)
   1959 {
   1960     GNode *cache;
   1961     const char *rp;
   1962     char *cp;
   1963 
   1964     if (!pathname || !pathname[0])
   1965 	return NULL;
   1966 
   1967     cache = get_cached_realpaths();
   1968 
   1969     if ((rp = Var_Value(pathname, cache, &cp)) != NULL) {
   1970 	/* a hit */
   1971 	strncpy(resolved, rp, MAXPATHLEN);
   1972 	resolved[MAXPATHLEN - 1] = '\0';
   1973     } else if ((rp = realpath(pathname, resolved)) != NULL) {
   1974 	Var_Set(pathname, rp, cache);
   1975     } /* else should we negative-cache? */
   1976 
   1977     bmake_free(cp);
   1978     return rp ? resolved : NULL;
   1979 }
   1980 
   1981 
   1982 static int
   1983 addErrorCMD(void *cmdp, void *gnp)
   1984 {
   1985     if (cmdp == NULL)
   1986 	return 1;			/* stop */
   1987     Var_Append(".ERROR_CMD", cmdp, VAR_GLOBAL);
   1988     return 0;
   1989 }
   1990 
   1991 /*
   1992  * Return true if we should die without noise.
   1993  * For example our failing child was a sub-make
   1994  * or failure happend elsewhere.
   1995  */
   1996 int
   1997 dieQuietly(GNode *gn, int bf)
   1998 {
   1999     static int quietly = -1;
   2000 
   2001     if (quietly < 0) {
   2002 	if (DEBUG(JOB) || getBoolean(".MAKE.DIE_QUIETLY", 1) == 0)
   2003 	    quietly = 0;
   2004 	else if (bf >= 0)
   2005 	    quietly = bf;
   2006 	else
   2007 	    quietly = (gn) ? ((gn->type  & (OP_MAKE)) != 0) : 0;
   2008     }
   2009     return quietly;
   2010 }
   2011 
   2012 void
   2013 PrintOnError(GNode *gn, const char *s)
   2014 {
   2015     static GNode *en = NULL;
   2016     const char *expr;
   2017     char *cp;
   2018 
   2019     if (DEBUG(HASH)) {
   2020 	Targ_Stats();
   2021 	Var_Stats();
   2022     }
   2023 
   2024     /* we generally want to keep quiet if a sub-make died */
   2025     if (dieQuietly(gn, -1))
   2026 	return;
   2027 
   2028     if (s)
   2029 	printf("%s", s);
   2030 
   2031     printf("\n%s: stopped in %s\n", progname, curdir);
   2032 
   2033     if (en)
   2034 	return;				/* we've been here! */
   2035     if (gn) {
   2036 	/*
   2037 	 * We can print this even if there is no .ERROR target.
   2038 	 */
   2039 	Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL);
   2040 	Var_Delete(".ERROR_CMD", VAR_GLOBAL);
   2041 	Lst_ForEachUntil(gn->commands, addErrorCMD, gn);
   2042     }
   2043     expr = "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}";
   2044     (void)Var_Subst(expr, VAR_GLOBAL, VARE_WANTRES, &cp);
   2045     /* TODO: handle errors */
   2046     printf("%s", cp);
   2047     free(cp);
   2048     fflush(stdout);
   2049 
   2050     /*
   2051      * Finally, see if there is a .ERROR target, and run it if so.
   2052      */
   2053     en = Targ_FindNode(".ERROR");
   2054     if (en) {
   2055 	en->type |= OP_SPECIAL;
   2056 	Compat_Make(en, en);
   2057     }
   2058 }
   2059 
   2060 void
   2061 Main_ExportMAKEFLAGS(Boolean first)
   2062 {
   2063     static Boolean once = TRUE;
   2064     const char *expr;
   2065     char *s;
   2066 
   2067     if (once != first)
   2068 	return;
   2069     once = FALSE;
   2070 
   2071     expr = "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}";
   2072     (void)Var_Subst(expr, VAR_CMD, VARE_WANTRES, &s);
   2073     /* TODO: handle errors */
   2074     if (s[0] != '\0') {
   2075 #ifdef POSIX
   2076 	setenv("MAKEFLAGS", s, 1);
   2077 #else
   2078 	setenv("MAKE", s, 1);
   2079 #endif
   2080     }
   2081 }
   2082 
   2083 char *
   2084 getTmpdir(void)
   2085 {
   2086     static char *tmpdir = NULL;
   2087 
   2088     if (!tmpdir) {
   2089 	struct stat st;
   2090 
   2091 	/*
   2092 	 * Honor $TMPDIR but only if it is valid.
   2093 	 * Ensure it ends with /.
   2094 	 */
   2095 	(void)Var_Subst("${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL,
   2096 			VARE_WANTRES, &tmpdir);
   2097 	/* TODO: handle errors */
   2098 	if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
   2099 	    free(tmpdir);
   2100 	    tmpdir = bmake_strdup(_PATH_TMP);
   2101 	}
   2102     }
   2103     return tmpdir;
   2104 }
   2105 
   2106 /*
   2107  * Create and open a temp file using "pattern".
   2108  * If "fnamep" is provided set it to a copy of the filename created.
   2109  * Otherwise unlink the file once open.
   2110  */
   2111 int
   2112 mkTempFile(const char *pattern, char **fnamep)
   2113 {
   2114     static char *tmpdir = NULL;
   2115     char tfile[MAXPATHLEN];
   2116     int fd;
   2117 
   2118     if (!pattern)
   2119 	pattern = TMPPAT;
   2120     if (!tmpdir)
   2121 	tmpdir = getTmpdir();
   2122     if (pattern[0] == '/') {
   2123 	snprintf(tfile, sizeof(tfile), "%s", pattern);
   2124     } else {
   2125 	snprintf(tfile, sizeof(tfile), "%s%s", tmpdir, pattern);
   2126     }
   2127     if ((fd = mkstemp(tfile)) < 0)
   2128 	Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
   2129     if (fnamep) {
   2130 	*fnamep = bmake_strdup(tfile);
   2131     } else {
   2132 	unlink(tfile);			/* we just want the descriptor */
   2133     }
   2134     return fd;
   2135 }
   2136 
   2137 /*
   2138  * Convert a string representation of a boolean.
   2139  * Anything that looks like "No", "False", "Off", "0" etc,
   2140  * is FALSE, otherwise TRUE.
   2141  */
   2142 Boolean
   2143 s2Boolean(const char *s, Boolean bf)
   2144 {
   2145     if (s) {
   2146 	switch(*s) {
   2147 	case '\0':			/* not set - the default wins */
   2148 	    break;
   2149 	case '0':
   2150 	case 'F':
   2151 	case 'f':
   2152 	case 'N':
   2153 	case 'n':
   2154 	    bf = FALSE;
   2155 	    break;
   2156 	case 'O':
   2157 	case 'o':
   2158 	    switch (s[1]) {
   2159 	    case 'F':
   2160 	    case 'f':
   2161 		bf = FALSE;
   2162 		break;
   2163 	    default:
   2164 		bf = TRUE;
   2165 		break;
   2166 	    }
   2167 	    break;
   2168 	default:
   2169 	    bf = TRUE;
   2170 	    break;
   2171 	}
   2172     }
   2173     return bf;
   2174 }
   2175 
   2176 /*
   2177  * Return a Boolean based on setting of a knob.
   2178  *
   2179  * If the knob is not set, the supplied default is the return value.
   2180  * If set, anything that looks or smells like "No", "False", "Off", "0" etc,
   2181  * is FALSE, otherwise TRUE.
   2182  */
   2183 Boolean
   2184 getBoolean(const char *name, Boolean fallback)
   2185 {
   2186     char *expr = str_concat3("${", name, ":U:tl}");
   2187     char *value;
   2188     Boolean res;
   2189 
   2190     (void)Var_Subst(expr, VAR_GLOBAL, VARE_WANTRES, &value);
   2191     /* TODO: handle errors */
   2192     res = s2Boolean(value, fallback);
   2193     free(value);
   2194     free(expr);
   2195     return res;
   2196 }
   2197