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