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