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