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