Home | History | Annotate | Line # | Download | only in make
main.c revision 1.29
      1 /*	$NetBSD: main.c,v 1.29 1996/05/28 23:34:41 christos Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
      5  * Copyright (c) 1988, 1989 by Adam de Boor
      6  * Copyright (c) 1989 by Berkeley Softworks
      7  * All rights reserved.
      8  *
      9  * This code is derived from software contributed to Berkeley by
     10  * Adam de Boor.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *	This product includes software developed by the University of
     23  *	California, Berkeley and its contributors.
     24  * 4. Neither the name of the University nor the names of its contributors
     25  *    may be used to endorse or promote products derived from this software
     26  *    without specific prior written permission.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     38  * SUCH DAMAGE.
     39  */
     40 
     41 #ifndef lint
     42 char copyright[] =
     43 "@(#) Copyright (c) 1989 The Regents of the University of California.\n\
     44  All rights reserved.\n";
     45 #endif /* not lint */
     46 
     47 #ifndef lint
     48 #if 0
     49 static char sccsid[] = "@(#)main.c	5.25 (Berkeley) 4/1/91";
     50 #else
     51 static char rcsid[] = "$NetBSD: main.c,v 1.29 1996/05/28 23:34:41 christos Exp $";
     52 #endif
     53 #endif /* not lint */
     54 
     55 /*-
     56  * main.c --
     57  *	The main file for this entire program. Exit routines etc
     58  *	reside here.
     59  *
     60  * Utility functions defined in this file:
     61  *	Main_ParseArgLine	Takes a line of arguments, breaks them and
     62  *				treats them as if they were given when first
     63  *				invoked. Used by the parse module to implement
     64  *				the .MFLAGS target.
     65  *
     66  *	Error			Print a tagged error message. The global
     67  *				MAKE variable must have been defined. This
     68  *				takes a format string and two optional
     69  *				arguments for it.
     70  *
     71  *	Fatal			Print an error message and exit. Also takes
     72  *				a format string and two arguments.
     73  *
     74  *	Punt			Aborts all jobs and exits with a message. Also
     75  *				takes a format string and two arguments.
     76  *
     77  *	Finish			Finish things up by printing the number of
     78  *				errors which occured, as passed to it, and
     79  *				exiting.
     80  */
     81 
     82 #include <sys/types.h>
     83 #include <sys/time.h>
     84 #include <sys/param.h>
     85 #include <sys/resource.h>
     86 #include <sys/signal.h>
     87 #include <sys/stat.h>
     88 #include <sys/utsname.h>
     89 #include <sys/wait.h>
     90 #include <errno.h>
     91 #include <fcntl.h>
     92 #include <stdio.h>
     93 #if __STDC__
     94 #include <stdarg.h>
     95 #else
     96 #include <varargs.h>
     97 #endif
     98 #include "make.h"
     99 #include "hash.h"
    100 #include "dir.h"
    101 #include "job.h"
    102 #include "pathnames.h"
    103 
    104 #ifndef	DEFMAXLOCAL
    105 #define	DEFMAXLOCAL DEFMAXJOBS
    106 #endif	/* DEFMAXLOCAL */
    107 
    108 #define	MAKEFLAGS	".MAKEFLAGS"
    109 
    110 Lst			create;		/* Targets to be made */
    111 time_t			now;		/* Time at start of make */
    112 GNode			*DEFAULT;	/* .DEFAULT node */
    113 Boolean			allPrecious;	/* .PRECIOUS given on line by itself */
    114 
    115 static Boolean		noBuiltins;	/* -r flag */
    116 static Lst		makefiles;	/* ordered list of makefiles to read */
    117 int			maxJobs;	/* -j argument */
    118 static int		maxLocal;	/* -L argument */
    119 Boolean			compatMake;	/* -B argument */
    120 Boolean			debug;		/* -d flag */
    121 Boolean			noExecute;	/* -n flag */
    122 Boolean			keepgoing;	/* -k flag */
    123 Boolean			queryFlag;	/* -q flag */
    124 Boolean			touchFlag;	/* -t flag */
    125 Boolean			usePipes;	/* !-P flag */
    126 Boolean			ignoreErrors;	/* -i flag */
    127 Boolean			beSilent;	/* -s flag */
    128 Boolean			oldVars;	/* variable substitution style */
    129 Boolean			checkEnvFirst;	/* -e flag */
    130 static Boolean		jobsRunning;	/* TRUE if the jobs might be running */
    131 
    132 static Boolean		ReadMakefile();
    133 static void		usage();
    134 
    135 static char *curdir;			/* startup directory */
    136 static char *objdir;			/* where we chdir'ed to */
    137 
    138 /*-
    139  * MainParseArgs --
    140  *	Parse a given argument vector. Called from main() and from
    141  *	Main_ParseArgLine() when the .MAKEFLAGS target is used.
    142  *
    143  *	XXX: Deal with command line overriding .MAKEFLAGS in makefile
    144  *
    145  * Results:
    146  *	None
    147  *
    148  * Side Effects:
    149  *	Various global and local flags will be set depending on the flags
    150  *	given
    151  */
    152 static void
    153 MainParseArgs(argc, argv)
    154 	int argc;
    155 	char **argv;
    156 {
    157 	extern int optind;
    158 	extern char *optarg;
    159 	int c;
    160 	int forceJobs = 0;
    161 
    162 	optind = 1;	/* since we're called more than once */
    163 #ifdef REMOTE
    164 # define OPTFLAGS "BD:I:L:PSd:ef:ij:km:nqrst"
    165 #else
    166 # define OPTFLAGS "BD:I:PSd:ef:ij:km:nqrst"
    167 #endif
    168 rearg:	while((c = getopt(argc, argv, OPTFLAGS)) != EOF) {
    169 		switch(c) {
    170 		case 'D':
    171 			Var_Set(optarg, "1", VAR_GLOBAL);
    172 			Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
    173 			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
    174 			break;
    175 		case 'I':
    176 			Parse_AddIncludeDir(optarg);
    177 			Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
    178 			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
    179 			break;
    180 		case 'B':
    181 			compatMake = TRUE;
    182 			break;
    183 #ifdef REMOTE
    184 		case 'L':
    185 			maxLocal = atoi(optarg);
    186 			Var_Append(MAKEFLAGS, "-L", VAR_GLOBAL);
    187 			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
    188 			break;
    189 #endif
    190 		case 'P':
    191 			usePipes = FALSE;
    192 			Var_Append(MAKEFLAGS, "-P", VAR_GLOBAL);
    193 			break;
    194 		case 'S':
    195 			keepgoing = FALSE;
    196 			Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
    197 			break;
    198 		case 'd': {
    199 			char *modules = optarg;
    200 
    201 			for (; *modules; ++modules)
    202 				switch (*modules) {
    203 				case 'A':
    204 					debug = ~0;
    205 					break;
    206 				case 'a':
    207 					debug |= DEBUG_ARCH;
    208 					break;
    209 				case 'c':
    210 					debug |= DEBUG_COND;
    211 					break;
    212 				case 'd':
    213 					debug |= DEBUG_DIR;
    214 					break;
    215 				case 'f':
    216 					debug |= DEBUG_FOR;
    217 					break;
    218 				case 'g':
    219 					if (modules[1] == '1') {
    220 						debug |= DEBUG_GRAPH1;
    221 						++modules;
    222 					}
    223 					else if (modules[1] == '2') {
    224 						debug |= DEBUG_GRAPH2;
    225 						++modules;
    226 					}
    227 					break;
    228 				case 'j':
    229 					debug |= DEBUG_JOB;
    230 					break;
    231 				case 'm':
    232 					debug |= DEBUG_MAKE;
    233 					break;
    234 				case 's':
    235 					debug |= DEBUG_SUFF;
    236 					break;
    237 				case 't':
    238 					debug |= DEBUG_TARG;
    239 					break;
    240 				case 'v':
    241 					debug |= DEBUG_VAR;
    242 					break;
    243 				default:
    244 					(void)fprintf(stderr,
    245 				"make: illegal argument to d option -- %c\n",
    246 					    *modules);
    247 					usage();
    248 				}
    249 			Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
    250 			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
    251 			break;
    252 		}
    253 		case 'e':
    254 			checkEnvFirst = TRUE;
    255 			Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
    256 			break;
    257 		case 'f':
    258 			(void)Lst_AtEnd(makefiles, (ClientData)optarg);
    259 			break;
    260 		case 'i':
    261 			ignoreErrors = TRUE;
    262 			Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
    263 			break;
    264 		case 'j':
    265 			forceJobs = TRUE;
    266 			maxJobs = atoi(optarg);
    267 #ifndef REMOTE
    268 			maxLocal = maxJobs;
    269 #endif
    270 			Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
    271 			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
    272 			break;
    273 		case 'k':
    274 			keepgoing = TRUE;
    275 			Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
    276 			break;
    277 		case 'm':
    278 			Dir_AddDir(sysIncPath, optarg);
    279 			Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
    280 			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
    281 			break;
    282 		case 'n':
    283 			noExecute = TRUE;
    284 			Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
    285 			break;
    286 		case 'q':
    287 			queryFlag = TRUE;
    288 			/* Kind of nonsensical, wot? */
    289 			Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
    290 			break;
    291 		case 'r':
    292 			noBuiltins = TRUE;
    293 			Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
    294 			break;
    295 		case 's':
    296 			beSilent = TRUE;
    297 			Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
    298 			break;
    299 		case 't':
    300 			touchFlag = TRUE;
    301 			Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
    302 			break;
    303 		default:
    304 		case '?':
    305 			usage();
    306 		}
    307 	}
    308 
    309 	/*
    310 	 * Be compatible if user did not specify -j and did not explicitly
    311 	 * turned compatibility on
    312 	 */
    313 	if (!compatMake && !forceJobs)
    314 		compatMake = TRUE;
    315 
    316 	oldVars = TRUE;
    317 
    318 	/*
    319 	 * See if the rest of the arguments are variable assignments and
    320 	 * perform them if so. Else take them to be targets and stuff them
    321 	 * on the end of the "create" list.
    322 	 */
    323 	for (argv += optind, argc -= optind; *argv; ++argv, --argc)
    324 		if (Parse_IsVar(*argv))
    325 			Parse_DoVar(*argv, VAR_CMD);
    326 		else {
    327 			if (!**argv)
    328 				Punt("illegal (null) argument.");
    329 			if (**argv == '-') {
    330 				if ((*argv)[1])
    331 					optind = 0;     /* -flag... */
    332 				else
    333 					optind = 1;     /* - */
    334 				goto rearg;
    335 			}
    336 			(void)Lst_AtEnd(create, (ClientData)strdup(*argv));
    337 		}
    338 }
    339 
    340 /*-
    341  * Main_ParseArgLine --
    342  *  	Used by the parse module when a .MFLAGS or .MAKEFLAGS target
    343  *	is encountered and by main() when reading the .MAKEFLAGS envariable.
    344  *	Takes a line of arguments and breaks it into its
    345  * 	component words and passes those words and the number of them to the
    346  *	MainParseArgs function.
    347  *	The line should have all its leading whitespace removed.
    348  *
    349  * Results:
    350  *	None
    351  *
    352  * Side Effects:
    353  *	Only those that come from the various arguments.
    354  */
    355 void
    356 Main_ParseArgLine(line)
    357 	char *line;			/* Line to fracture */
    358 {
    359 	char **argv;			/* Manufactured argument vector */
    360 	int argc;			/* Number of arguments in argv */
    361 
    362 	if (line == NULL)
    363 		return;
    364 	for (; *line == ' '; ++line)
    365 		continue;
    366 	if (!*line)
    367 		return;
    368 
    369 	argv = brk_string(line, &argc, TRUE);
    370 	MainParseArgs(argc, argv);
    371 }
    372 
    373 /*-
    374  * main --
    375  *	The main function, for obvious reasons. Initializes variables
    376  *	and a few modules, then parses the arguments give it in the
    377  *	environment and on the command line. Reads the system makefile
    378  *	followed by either Makefile, makefile or the file given by the
    379  *	-f argument. Sets the .MAKEFLAGS PMake variable based on all the
    380  *	flags it has received by then uses either the Make or the Compat
    381  *	module to create the initial list of targets.
    382  *
    383  * Results:
    384  *	If -q was given, exits -1 if anything was out-of-date. Else it exits
    385  *	0.
    386  *
    387  * Side Effects:
    388  *	The program exits when done. Targets are created. etc. etc. etc.
    389  */
    390 int
    391 main(argc, argv)
    392 	int argc;
    393 	char **argv;
    394 {
    395 	Lst targs;	/* target nodes to create -- passed to Make_Init */
    396 	Boolean outOfDate = TRUE; 	/* FALSE if all targets up to date */
    397 	struct stat sb, sa;
    398 	char *p, *p1, *path, *pwd, *getenv(), *getwd();
    399 	char mdpath[MAXPATHLEN + 1];
    400 	char obpath[MAXPATHLEN + 1];
    401 	char cdpath[MAXPATHLEN + 1];
    402 	struct utsname utsname;
    403     	char *machine = getenv("MACHINE");
    404 	Lst sysMkPath;			/* Path of sys.mk */
    405 	char *cp = NULL, *start;
    406 					/* avoid faults on read-only strings */
    407 	static char syspath[] = _PATH_DEFSYSPATH;
    408 
    409 #ifdef RLIMIT_NOFILE
    410 	/*
    411 	 * get rid of resource limit on file descriptors
    412 	 */
    413 	{
    414 		struct rlimit rl;
    415 		if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
    416 		    rl.rlim_cur != rl.rlim_max) {
    417 			rl.rlim_cur = rl.rlim_max;
    418 			(void) setrlimit(RLIMIT_NOFILE, &rl);
    419 		}
    420 	}
    421 #endif
    422 	/*
    423 	 * Find where we are and take care of PWD for the automounter...
    424 	 * All this code is so that we know where we are when we start up
    425 	 * on a different machine with pmake.
    426 	 */
    427 	curdir = cdpath;
    428 	if (getcwd(curdir, MAXPATHLEN) == NULL) {
    429 		(void)fprintf(stderr, "make: %s.\n", strerror(errno));
    430 		exit(2);
    431 	}
    432 
    433 	if (stat(curdir, &sa) == -1) {
    434 	    (void)fprintf(stderr, "make: %s: %s.\n",
    435 			  curdir, strerror(errno));
    436 	    exit(2);
    437 	}
    438 
    439 	if ((pwd = getenv("PWD")) != NULL) {
    440 	    if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
    441 		sa.st_dev == sb.st_dev)
    442 		(void) strcpy(curdir, pwd);
    443 	}
    444 
    445 	/*
    446 	 * Get the name of this type of MACHINE from utsname
    447 	 * so we can share an executable for similar machines.
    448 	 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
    449 	 *
    450 	 * Note that while MACHINE is decided at run-time,
    451 	 * MACHINE_ARCH is always known at compile time.
    452 	 */
    453     	if (!machine) {
    454 #ifndef MACHINE
    455 	    if (uname(&utsname) == -1) {
    456 		    perror("make: uname");
    457 		    exit(2);
    458 	    }
    459 	    machine = utsname.machine;
    460 #else
    461 	    machine = MACHINE;
    462 #endif
    463 	}
    464 
    465 	/*
    466 	 * if the MAKEOBJDIR (or by default, the _PATH_OBJDIR) directory
    467 	 * exists, change into it and build there.  Once things are
    468 	 * initted, have to add the original directory to the search path,
    469 	 * and modify the paths for the Makefiles apropriately.  The
    470 	 * current directory is also placed as a variable for make scripts.
    471 	 */
    472 	if (!(path = getenv("MAKEOBJDIR"))) {
    473 		path = _PATH_OBJDIR;
    474 		(void) sprintf(mdpath, "%s.%s", path, machine);
    475 	}
    476 	else
    477 		(void) strncpy(mdpath, path, MAXPATHLEN + 1);
    478 
    479 	if (stat(mdpath, &sb) == 0 && S_ISDIR(sb.st_mode)) {
    480 
    481 		if (chdir(mdpath)) {
    482 			(void)fprintf(stderr, "make warning: %s: %s.\n",
    483 				      mdpath, strerror(errno));
    484 			objdir = curdir;
    485 		}
    486 		else {
    487 			if (mdpath[0] != '/') {
    488 				(void) sprintf(obpath, "%s/%s", curdir, mdpath);
    489 				objdir = obpath;
    490 			}
    491 			else
    492 				objdir = mdpath;
    493 		}
    494 	}
    495 	else {
    496 		if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
    497 
    498 			if (chdir(path)) {
    499 				(void)fprintf(stderr, "make warning: %s: %s.\n",
    500 					      path, strerror(errno));
    501 				objdir = curdir;
    502 			}
    503 			else {
    504 				if (path[0] != '/') {
    505 					(void) sprintf(obpath, "%s/%s", curdir,
    506 						       path);
    507 					objdir = obpath;
    508 				}
    509 				else
    510 					objdir = obpath;
    511 			}
    512 		}
    513 		else
    514 			objdir = curdir;
    515 	}
    516 
    517 	setenv("PWD", objdir, 1);
    518 
    519 	create = Lst_Init(FALSE);
    520 	makefiles = Lst_Init(FALSE);
    521 	beSilent = FALSE;		/* Print commands as executed */
    522 	ignoreErrors = FALSE;		/* Pay attention to non-zero returns */
    523 	noExecute = FALSE;		/* Execute all commands */
    524 	keepgoing = FALSE;		/* Stop on error */
    525 	allPrecious = FALSE;		/* Remove targets when interrupted */
    526 	queryFlag = FALSE;		/* This is not just a check-run */
    527 	noBuiltins = FALSE;		/* Read the built-in rules */
    528 	touchFlag = FALSE;		/* Actually update targets */
    529 	usePipes = TRUE;		/* Catch child output in pipes */
    530 	debug = 0;			/* No debug verbosity, please. */
    531 	jobsRunning = FALSE;
    532 
    533 	maxLocal = DEFMAXLOCAL;		/* Set default local max concurrency */
    534 #ifdef REMOTE
    535 	maxJobs = DEFMAXJOBS;		/* Set default max concurrency */
    536 #else
    537 	maxJobs = maxLocal;
    538 #endif
    539 	compatMake = FALSE;		/* No compat mode */
    540 
    541 
    542 	/*
    543 	 * Initialize the parsing, directory and variable modules to prepare
    544 	 * for the reading of inclusion paths and variable settings on the
    545 	 * command line
    546 	 */
    547 	Dir_Init();		/* Initialize directory structures so -I flags
    548 				 * can be processed correctly */
    549 	Parse_Init();		/* Need to initialize the paths of #include
    550 				 * directories */
    551 	Var_Init();		/* As well as the lists of variables for
    552 				 * parsing arguments */
    553         str_init();
    554 	if (objdir != curdir)
    555 		Dir_AddDir(dirSearchPath, curdir);
    556 	Var_Set(".CURDIR", curdir, VAR_GLOBAL);
    557 	Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
    558 
    559 	/*
    560 	 * Initialize various variables.
    561 	 *	MAKE also gets this name, for compatibility
    562 	 *	.MAKEFLAGS gets set to the empty string just in case.
    563 	 *	MFLAGS also gets initialized empty, for compatibility.
    564 	 */
    565 	Var_Set("MAKE", argv[0], VAR_GLOBAL);
    566 	Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
    567 	Var_Set("MFLAGS", "", VAR_GLOBAL);
    568 	Var_Set("MACHINE", machine, VAR_GLOBAL);
    569 #ifdef MACHINE_ARCH
    570 	Var_Set("MACHINE_ARCH", MACHINE_ARCH, VAR_GLOBAL);
    571 #endif
    572 
    573 	/*
    574 	 * First snag any flags out of the MAKE environment variable.
    575 	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
    576 	 * in a different format).
    577 	 */
    578 #ifdef POSIX
    579 	Main_ParseArgLine(getenv("MAKEFLAGS"));
    580 #else
    581 	Main_ParseArgLine(getenv("MAKE"));
    582 #endif
    583 
    584 	MainParseArgs(argc, argv);
    585 
    586 	/*
    587 	 * Initialize archive, target and suffix modules in preparation for
    588 	 * parsing the makefile(s)
    589 	 */
    590 	Arch_Init();
    591 	Targ_Init();
    592 	Suff_Init();
    593 
    594 	DEFAULT = NILGNODE;
    595 	(void)time(&now);
    596 
    597 	/*
    598 	 * Set up the .TARGETS variable to contain the list of targets to be
    599 	 * created. If none specified, make the variable empty -- the parser
    600 	 * will fill the thing in with the default or .MAIN target.
    601 	 */
    602 	if (!Lst_IsEmpty(create)) {
    603 		LstNode ln;
    604 
    605 		for (ln = Lst_First(create); ln != NILLNODE;
    606 		    ln = Lst_Succ(ln)) {
    607 			char *name = (char *)Lst_Datum(ln);
    608 
    609 			Var_Append(".TARGETS", name, VAR_GLOBAL);
    610 		}
    611 	} else
    612 		Var_Set(".TARGETS", "", VAR_GLOBAL);
    613 
    614 
    615 	/*
    616 	 * If no user-supplied system path was given (through the -m option)
    617 	 * add the directories from the DEFSYSPATH (more than one may be given
    618 	 * as dir1:...:dirn) to the system include path.
    619 	 */
    620 	if (Lst_IsEmpty(sysIncPath)) {
    621 		for (start = syspath; *start != '\0'; start = cp) {
    622 			for (cp = start; *cp != '\0' && *cp != ':'; cp++)
    623 				continue;
    624 			if (*cp == '\0') {
    625 				Dir_AddDir(sysIncPath, start);
    626 			} else {
    627 				*cp++ = '\0';
    628 				Dir_AddDir(sysIncPath, start);
    629 			}
    630 		}
    631 	}
    632 
    633 	/*
    634 	 * Read in the built-in rules first, followed by the specified
    635 	 * makefile, if it was (makefile != (char *) NULL), or the default
    636 	 * Makefile and makefile, in that order, if it wasn't.
    637 	 */
    638 	if (!noBuiltins) {
    639 		LstNode ln;
    640 
    641 		sysMkPath = Lst_Init (FALSE);
    642 		Dir_Expand (_PATH_DEFSYSMK, sysIncPath, sysMkPath);
    643 		if (Lst_IsEmpty(sysMkPath))
    644 			Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
    645 		ln = Lst_Find(sysMkPath, (ClientData)NULL, ReadMakefile);
    646 		if (ln != NILLNODE)
    647 			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
    648 	}
    649 
    650 	if (!Lst_IsEmpty(makefiles)) {
    651 		LstNode ln;
    652 
    653 		ln = Lst_Find(makefiles, (ClientData)NULL, ReadMakefile);
    654 		if (ln != NILLNODE)
    655 			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
    656 	} else if (!ReadMakefile("makefile"))
    657 		(void)ReadMakefile("Makefile");
    658 
    659 	(void)ReadMakefile(".depend");
    660 
    661 	Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
    662 	if (p1)
    663 	    free(p1);
    664 
    665 	/* Install all the flags into the MAKE envariable. */
    666 	if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
    667 #ifdef POSIX
    668 		setenv("MAKEFLAGS", p, 1);
    669 #else
    670 		setenv("MAKE", p, 1);
    671 #endif
    672 	if (p1)
    673 	    free(p1);
    674 
    675 	/*
    676 	 * For compatibility, look at the directories in the VPATH variable
    677 	 * and add them to the search path, if the variable is defined. The
    678 	 * variable's value is in the same format as the PATH envariable, i.e.
    679 	 * <directory>:<directory>:<directory>...
    680 	 */
    681 	if (Var_Exists("VPATH", VAR_CMD)) {
    682 		char *vpath, *path, *cp, savec;
    683 		/*
    684 		 * GCC stores string constants in read-only memory, but
    685 		 * Var_Subst will want to write this thing, so store it
    686 		 * in an array
    687 		 */
    688 		static char VPATH[] = "${VPATH}";
    689 
    690 		vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
    691 		path = vpath;
    692 		do {
    693 			/* skip to end of directory */
    694 			for (cp = path; *cp != ':' && *cp != '\0'; cp++)
    695 				continue;
    696 			/* Save terminator character so know when to stop */
    697 			savec = *cp;
    698 			*cp = '\0';
    699 			/* Add directory to search path */
    700 			Dir_AddDir(dirSearchPath, path);
    701 			*cp = savec;
    702 			path = cp + 1;
    703 		} while (savec == ':');
    704 		(void)free((Address)vpath);
    705 	}
    706 
    707 	/*
    708 	 * Now that all search paths have been read for suffixes et al, it's
    709 	 * time to add the default search path to their lists...
    710 	 */
    711 	Suff_DoPaths();
    712 
    713 	/* print the initial graph, if the user requested it */
    714 	if (DEBUG(GRAPH1))
    715 		Targ_PrintGraph(1);
    716 
    717 	/*
    718 	 * Have now read the entire graph and need to make a list of targets
    719 	 * to create. If none was given on the command line, we consult the
    720 	 * parsing module to find the main target(s) to create.
    721 	 */
    722 	if (Lst_IsEmpty(create))
    723 		targs = Parse_MainName();
    724 	else
    725 		targs = Targ_FindList(create, TARG_CREATE);
    726 
    727 	if (!compatMake) {
    728 		/*
    729 		 * Initialize job module before traversing the graph, now that
    730 		 * any .BEGIN and .END targets have been read.  This is done
    731 		 * only if the -q flag wasn't given (to prevent the .BEGIN from
    732 		 * being executed should it exist).
    733 		 */
    734 		if (!queryFlag) {
    735 			if (maxLocal == -1)
    736 				maxLocal = maxJobs;
    737 			Job_Init(maxJobs, maxLocal);
    738 			jobsRunning = TRUE;
    739 		}
    740 
    741 		/* Traverse the graph, checking on all the targets */
    742 		outOfDate = Make_Run(targs);
    743 	} else
    744 		/*
    745 		 * Compat_Init will take care of creating all the targets as
    746 		 * well as initializing the module.
    747 		 */
    748 		Compat_Run(targs);
    749 
    750 	Lst_Destroy(targs, NOFREE);
    751 	Lst_Destroy(makefiles, NOFREE);
    752 	Lst_Destroy(create, (void (*) __P((ClientData))) free);
    753 
    754 	/* print the graph now it's been processed if the user requested it */
    755 	if (DEBUG(GRAPH2))
    756 		Targ_PrintGraph(2);
    757 
    758 	Suff_End();
    759         Targ_End();
    760 	Arch_End();
    761 	str_end();
    762 	Var_End();
    763 	Parse_End();
    764 	Dir_End();
    765 
    766 	if (queryFlag && outOfDate)
    767 		return(1);
    768 	else
    769 		return(0);
    770 }
    771 
    772 /*-
    773  * ReadMakefile  --
    774  *	Open and parse the given makefile.
    775  *
    776  * Results:
    777  *	TRUE if ok. FALSE if couldn't open file.
    778  *
    779  * Side Effects:
    780  *	lots
    781  */
    782 static Boolean
    783 ReadMakefile(fname)
    784 	char *fname;		/* makefile to read */
    785 {
    786 	extern Lst parseIncPath;
    787 	FILE *stream;
    788 	char *name, path[MAXPATHLEN + 1];
    789 
    790 	if (!strcmp(fname, "-")) {
    791 		Parse_File("(stdin)", stdin);
    792 		Var_Set("MAKEFILE", "", VAR_GLOBAL);
    793 	} else {
    794 		if ((stream = fopen(fname, "r")) != NULL)
    795 			goto found;
    796 		/* if we've chdir'd, rebuild the path name */
    797 		if (curdir != objdir && *fname != '/') {
    798 			(void)sprintf(path, "%s/%s", curdir, fname);
    799 			if ((stream = fopen(path, "r")) != NULL) {
    800 				fname = path;
    801 				goto found;
    802 			}
    803 		}
    804 		/* look in -I and system include directories. */
    805 		name = Dir_FindFile(fname, parseIncPath);
    806 		if (!name)
    807 			name = Dir_FindFile(fname, sysIncPath);
    808 		if (!name || !(stream = fopen(name, "r")))
    809 			return(FALSE);
    810 		fname = name;
    811 		/*
    812 		 * set the MAKEFILE variable desired by System V fans -- the
    813 		 * placement of the setting here means it gets set to the last
    814 		 * makefile specified, as it is set by SysV make.
    815 		 */
    816 found:		Var_Set("MAKEFILE", fname, VAR_GLOBAL);
    817 		Parse_File(fname, stream);
    818 		(void)fclose(stream);
    819 	}
    820 	return(TRUE);
    821 }
    822 
    823 /*-
    824  * Cmd_Exec --
    825  *	Execute the command in cmd, and return the output of that command
    826  *	in a string.
    827  *
    828  * Results:
    829  *	A string containing the output of the command, or the empty string
    830  *	If err is not NULL, it contains the reason for the command failure
    831  *
    832  * Side Effects:
    833  *	The string must be freed by the caller.
    834  */
    835 char *
    836 Cmd_Exec(cmd, err)
    837     char *cmd;
    838     char **err;
    839 {
    840     char	*args[4];   	/* Args for invoking the shell */
    841     int 	fds[2];	    	/* Pipe streams */
    842     int 	cpid;	    	/* Child PID */
    843     int 	pid;	    	/* PID from wait() */
    844     char	*res;		/* result */
    845     int		status;		/* command exit status */
    846     Buffer	buf;		/* buffer to store the result */
    847     char	*cp;
    848     int		cc;
    849 
    850 
    851     *err = NULL;
    852 
    853     /*
    854      * Set up arguments for shell
    855      */
    856     args[0] = "sh";
    857     args[1] = "-c";
    858     args[2] = cmd;
    859     args[3] = NULL;
    860 
    861     /*
    862      * Open a pipe for fetching its output
    863      */
    864     if (pipe(fds) == -1) {
    865 	*err = "Couldn't create pipe for \"%s\"";
    866 	goto bad;
    867     }
    868 
    869     /*
    870      * Fork
    871      */
    872     switch (cpid = vfork()) {
    873     case 0:
    874 	/*
    875 	 * Close input side of pipe
    876 	 */
    877 	(void) close(fds[0]);
    878 
    879 	/*
    880 	 * Duplicate the output stream to the shell's output, then
    881 	 * shut the extra thing down. Note we don't fetch the error
    882 	 * stream...why not? Why?
    883 	 */
    884 	(void) dup2(fds[1], 1);
    885 	(void) close(fds[1]);
    886 
    887 	(void) execv("/bin/sh", args);
    888 	_exit(1);
    889 	/*NOTREACHED*/
    890 
    891     case -1:
    892 	*err = "Couldn't exec \"%s\"";
    893 	goto bad;
    894 
    895     default:
    896 	/*
    897 	 * No need for the writing half
    898 	 */
    899 	(void) close(fds[1]);
    900 
    901 	buf = Buf_Init (MAKE_BSIZE);
    902 
    903 	do {
    904 	    char   result[BUFSIZ];
    905 	    cc = read(fds[0], result, sizeof(result));
    906 	    if (cc > 0)
    907 		Buf_AddBytes(buf, cc, (Byte *) result);
    908 	}
    909 	while (cc > 0 || (cc == -1 && errno == EINTR));
    910 
    911 	/*
    912 	 * Close the input side of the pipe.
    913 	 */
    914 	(void) close(fds[0]);
    915 
    916 	/*
    917 	 * Wait for the process to exit.
    918 	 */
    919 	while(((pid = wait(&status)) != cpid) && (pid >= 0))
    920 	    continue;
    921 
    922 	res = (char *)Buf_GetAll (buf, &cc);
    923 	Buf_Destroy (buf, FALSE);
    924 
    925 	if (cc == 0)
    926 	    *err = "Couldn't read shell's output for \"%s\"";
    927 
    928 	if (status)
    929 	    *err = "\"%s\" returned non-zero status";
    930 
    931 	/*
    932 	 * Null-terminate the result, convert newlines to spaces and
    933 	 * install it in the variable.
    934 	 */
    935 	res[cc] = '\0';
    936 	cp = &res[cc] - 1;
    937 
    938 	if (*cp == '\n') {
    939 	    /*
    940 	     * A final newline is just stripped
    941 	     */
    942 	    *cp-- = '\0';
    943 	}
    944 	while (cp >= res) {
    945 	    if (*cp == '\n') {
    946 		*cp = ' ';
    947 	    }
    948 	    cp--;
    949 	}
    950 	break;
    951     }
    952     return res;
    953 bad:
    954     res = emalloc(1);
    955     *res = '\0';
    956     return res;
    957 }
    958 
    959 /*-
    960  * Error --
    961  *	Print an error message given its format.
    962  *
    963  * Results:
    964  *	None.
    965  *
    966  * Side Effects:
    967  *	The message is printed.
    968  */
    969 /* VARARGS */
    970 void
    971 #if __STDC__
    972 Error(char *fmt, ...)
    973 #else
    974 Error(va_alist)
    975 	va_dcl
    976 #endif
    977 {
    978 	va_list ap;
    979 #if __STDC__
    980 	va_start(ap, fmt);
    981 #else
    982 	char *fmt;
    983 
    984 	va_start(ap);
    985 	fmt = va_arg(ap, char *);
    986 #endif
    987 	(void)vfprintf(stderr, fmt, ap);
    988 	va_end(ap);
    989 	(void)fprintf(stderr, "\n");
    990 	(void)fflush(stderr);
    991 }
    992 
    993 /*-
    994  * Fatal --
    995  *	Produce a Fatal error message. If jobs are running, waits for them
    996  *	to finish.
    997  *
    998  * Results:
    999  *	None
   1000  *
   1001  * Side Effects:
   1002  *	The program exits
   1003  */
   1004 /* VARARGS */
   1005 void
   1006 #if __STDC__
   1007 Fatal(char *fmt, ...)
   1008 #else
   1009 Fatal(va_alist)
   1010 	va_dcl
   1011 #endif
   1012 {
   1013 	va_list ap;
   1014 #if __STDC__
   1015 	va_start(ap, fmt);
   1016 #else
   1017 	char *fmt;
   1018 
   1019 	va_start(ap);
   1020 	fmt = va_arg(ap, char *);
   1021 #endif
   1022 	if (jobsRunning)
   1023 		Job_Wait();
   1024 
   1025 	(void)vfprintf(stderr, fmt, ap);
   1026 	va_end(ap);
   1027 	(void)fprintf(stderr, "\n");
   1028 	(void)fflush(stderr);
   1029 
   1030 	if (DEBUG(GRAPH2))
   1031 		Targ_PrintGraph(2);
   1032 	exit(2);		/* Not 1 so -q can distinguish error */
   1033 }
   1034 
   1035 /*
   1036  * Punt --
   1037  *	Major exception once jobs are being created. Kills all jobs, prints
   1038  *	a message and exits.
   1039  *
   1040  * Results:
   1041  *	None
   1042  *
   1043  * Side Effects:
   1044  *	All children are killed indiscriminately and the program Lib_Exits
   1045  */
   1046 /* VARARGS */
   1047 void
   1048 #if __STDC__
   1049 Punt(char *fmt, ...)
   1050 #else
   1051 Punt(va_alist)
   1052 	va_dcl
   1053 #endif
   1054 {
   1055 	va_list ap;
   1056 #if __STDC__
   1057 	va_start(ap, fmt);
   1058 #else
   1059 	char *fmt;
   1060 
   1061 	va_start(ap);
   1062 	fmt = va_arg(ap, char *);
   1063 #endif
   1064 
   1065 	(void)fprintf(stderr, "make: ");
   1066 	(void)vfprintf(stderr, fmt, ap);
   1067 	va_end(ap);
   1068 	(void)fprintf(stderr, "\n");
   1069 	(void)fflush(stderr);
   1070 
   1071 	DieHorribly();
   1072 }
   1073 
   1074 /*-
   1075  * DieHorribly --
   1076  *	Exit without giving a message.
   1077  *
   1078  * Results:
   1079  *	None
   1080  *
   1081  * Side Effects:
   1082  *	A big one...
   1083  */
   1084 void
   1085 DieHorribly()
   1086 {
   1087 	if (jobsRunning)
   1088 		Job_AbortAll();
   1089 	if (DEBUG(GRAPH2))
   1090 		Targ_PrintGraph(2);
   1091 	exit(2);		/* Not 1, so -q can distinguish error */
   1092 }
   1093 
   1094 /*
   1095  * Finish --
   1096  *	Called when aborting due to errors in child shell to signal
   1097  *	abnormal exit.
   1098  *
   1099  * Results:
   1100  *	None
   1101  *
   1102  * Side Effects:
   1103  *	The program exits
   1104  */
   1105 void
   1106 Finish(errors)
   1107 	int errors;	/* number of errors encountered in Make_Make */
   1108 {
   1109 	Fatal("%d error%s", errors, errors == 1 ? "" : "s");
   1110 }
   1111 
   1112 /*
   1113  * emalloc --
   1114  *	malloc, but die on error.
   1115  */
   1116 void *
   1117 emalloc(len)
   1118 	size_t len;
   1119 {
   1120 	void *p;
   1121 
   1122 	if ((p = malloc(len)) == NULL)
   1123 		enomem();
   1124 	return(p);
   1125 }
   1126 
   1127 /*
   1128  * erealloc --
   1129  *	realloc, but die on error.
   1130  */
   1131 void *
   1132 erealloc(ptr, size)
   1133 	void *ptr;
   1134 	size_t size;
   1135 {
   1136 	if ((ptr = realloc(ptr, size)) == NULL)
   1137 		enomem();
   1138 	return(ptr);
   1139 }
   1140 
   1141 /*
   1142  * enomem --
   1143  *	die when out of memory.
   1144  */
   1145 void
   1146 enomem()
   1147 {
   1148 	(void)fprintf(stderr, "make: %s.\n", strerror(errno));
   1149 	exit(2);
   1150 }
   1151 
   1152 /*
   1153  * enunlink --
   1154  *	Remove a file carefully, avoiding directories.
   1155  */
   1156 int
   1157 eunlink(file)
   1158 	const char *file;
   1159 {
   1160 	struct stat st;
   1161 
   1162 	if (lstat(file, &st) == -1)
   1163 		return -1;
   1164 
   1165 	if (S_ISDIR(st.st_mode)) {
   1166 		errno = EISDIR;
   1167 		return -1;
   1168 	}
   1169 	return unlink(file);
   1170 }
   1171 
   1172 /*
   1173  * usage --
   1174  *	exit with usage message
   1175  */
   1176 static void
   1177 usage()
   1178 {
   1179 	(void)fprintf(stderr,
   1180 "usage: make [-eiknqrst] [-D variable] [-d flags] [-f makefile ]\n\
   1181             [-I directory] [-j max_jobs] [-m directory] [variable=value]\n");
   1182 	exit(2);
   1183 }
   1184 
   1185 
   1186 int
   1187 PrintAddr(a, b)
   1188     ClientData a;
   1189     ClientData b;
   1190 {
   1191     printf("%lx ", (unsigned long) a);
   1192     return b ? 0 : 0;
   1193 }
   1194