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