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