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