xref: /netbsd-src/usr.bin/make/main.c (revision d0fed6c87ddc40a8bffa6f99e7433ddfc864dd83)
1 /*	$NetBSD: main.c,v 1.34 1997/03/24 20:56:36 gwr 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.34 1997/03/24 20:56:36 gwr 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 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 	char *machine_arch = getenv("MACHINE_ARCH");
445 	Lst sysMkPath;			/* Path of sys.mk */
446 	char *cp = NULL, *start;
447 					/* avoid faults on read-only strings */
448 	static char syspath[] = _PATH_DEFSYSPATH;
449 
450 #ifdef RLIMIT_NOFILE
451 	/*
452 	 * get rid of resource limit on file descriptors
453 	 */
454 	{
455 		struct rlimit rl;
456 		if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
457 		    rl.rlim_cur != rl.rlim_max) {
458 			rl.rlim_cur = rl.rlim_max;
459 			(void) setrlimit(RLIMIT_NOFILE, &rl);
460 		}
461 	}
462 #endif
463 	/*
464 	 * Find where we are and take care of PWD for the automounter...
465 	 * All this code is so that we know where we are when we start up
466 	 * on a different machine with pmake.
467 	 */
468 	curdir = cdpath;
469 	if (getcwd(curdir, MAXPATHLEN) == NULL) {
470 		(void)fprintf(stderr, "make: %s.\n", strerror(errno));
471 		exit(2);
472 	}
473 
474 	if (stat(curdir, &sa) == -1) {
475 	    (void)fprintf(stderr, "make: %s: %s.\n",
476 			  curdir, strerror(errno));
477 	    exit(2);
478 	}
479 
480 	if ((pwd = getenv("PWD")) != NULL) {
481 	    if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
482 		sa.st_dev == sb.st_dev)
483 		(void) strcpy(curdir, pwd);
484 	}
485 
486 	/*
487 	 * Get the name of this type of MACHINE from utsname
488 	 * so we can share an executable for similar machines.
489 	 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
490 	 *
491 	 * Note that both MACHINE and MACHINE_ARCH are decided at
492 	 * run-time.
493 	 */
494 	if (!machine) {
495 #ifndef MAKE_BOOTSTRAP
496 	    struct utsname utsname;
497 
498 	    if (uname(&utsname) == -1) {
499 		    perror("make: uname");
500 		    exit(2);
501 	    }
502 	    machine = utsname.machine;
503 #else
504 	    machine = MACHINE;
505 #endif
506 	}
507 
508 	if (!machine_arch) {
509 #ifndef MACHINE_ARCH
510 	    machine_arch = "unknown";	/* XXX: no uname -p yet */
511 #else
512 	    machine_arch = MACHINE_ARCH;
513 #endif
514 	}
515 
516 	/*
517 	 * If the MAKEOBJDIR (or by default, the _PATH_OBJDIR) directory
518 	 * exists, change into it and build there.  (If a .${MACHINE} suffix
519 	 * exists, use that directory instead).
520 	 * Otherwise check MAKEOBJDIRPREFIX`cwd` (or by default,
521 	 * _PATH_OBJDIRPREFIX`cwd`) and build there if it exists.
522 	 * If all fails, use the current directory to build.
523 	 *
524 	 * Once things are initted,
525 	 * have to add the original directory to the search path,
526 	 * and modify the paths for the Makefiles apropriately.  The
527 	 * current directory is also placed as a variable for make scripts.
528 	 */
529 	if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
530 		if (!(path = getenv("MAKEOBJDIR"))) {
531 			path = _PATH_OBJDIR;
532 			pathp = _PATH_OBJDIRPREFIX;
533 			(void) snprintf(mdpath, MAXPATHLEN, "%s.%s",
534 					path, machine);
535 			if (!(objdir = chdir_verify_path(mdpath, obpath)))
536 				if (!(objdir=chdir_verify_path(path, obpath))) {
537 					(void) snprintf(mdpath, MAXPATHLEN,
538 							"%s%s", pathp, curdir);
539 					if (!(objdir=chdir_verify_path(mdpath,
540 								       obpath)))
541 						objdir = curdir;
542 				}
543 		}
544 		else if (!(objdir = chdir_verify_path(path, obpath)))
545 			objdir = curdir;
546 	}
547 	else {
548 		(void) snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
549 		if (!(objdir = chdir_verify_path(mdpath, obpath)))
550 			objdir = curdir;
551 	}
552 
553 	setenv("PWD", objdir, 1);
554 
555 	create = Lst_Init(FALSE);
556 	makefiles = Lst_Init(FALSE);
557 	printVars = FALSE;
558 	variables = Lst_Init(FALSE);
559 	beSilent = FALSE;		/* Print commands as executed */
560 	ignoreErrors = FALSE;		/* Pay attention to non-zero returns */
561 	noExecute = FALSE;		/* Execute all commands */
562 	keepgoing = FALSE;		/* Stop on error */
563 	allPrecious = FALSE;		/* Remove targets when interrupted */
564 	queryFlag = FALSE;		/* This is not just a check-run */
565 	noBuiltins = FALSE;		/* Read the built-in rules */
566 	touchFlag = FALSE;		/* Actually update targets */
567 	usePipes = TRUE;		/* Catch child output in pipes */
568 	debug = 0;			/* No debug verbosity, please. */
569 	jobsRunning = FALSE;
570 
571 	maxLocal = DEFMAXLOCAL;		/* Set default local max concurrency */
572 #ifdef REMOTE
573 	maxJobs = DEFMAXJOBS;		/* Set default max concurrency */
574 #else
575 	maxJobs = maxLocal;
576 #endif
577 	compatMake = FALSE;		/* No compat mode */
578 
579 
580 	/*
581 	 * Initialize the parsing, directory and variable modules to prepare
582 	 * for the reading of inclusion paths and variable settings on the
583 	 * command line
584 	 */
585 	Dir_Init();		/* Initialize directory structures so -I flags
586 				 * can be processed correctly */
587 	Parse_Init();		/* Need to initialize the paths of #include
588 				 * directories */
589 	Var_Init();		/* As well as the lists of variables for
590 				 * parsing arguments */
591         str_init();
592 	if (objdir != curdir)
593 		Dir_AddDir(dirSearchPath, curdir);
594 	Var_Set(".CURDIR", curdir, VAR_GLOBAL);
595 	Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
596 
597 	/*
598 	 * Initialize various variables.
599 	 *	MAKE also gets this name, for compatibility
600 	 *	.MAKEFLAGS gets set to the empty string just in case.
601 	 *	MFLAGS also gets initialized empty, for compatibility.
602 	 */
603 	Var_Set("MAKE", argv[0], VAR_GLOBAL);
604 	Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
605 	Var_Set("MFLAGS", "", VAR_GLOBAL);
606 	Var_Set("MACHINE", machine, VAR_GLOBAL);
607 	Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
608 
609 	/*
610 	 * First snag any flags out of the MAKE environment variable.
611 	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
612 	 * in a different format).
613 	 */
614 #ifdef POSIX
615 	Main_ParseArgLine(getenv("MAKEFLAGS"));
616 #else
617 	Main_ParseArgLine(getenv("MAKE"));
618 #endif
619 
620 	MainParseArgs(argc, argv);
621 
622 	/*
623 	 * Initialize archive, target and suffix modules in preparation for
624 	 * parsing the makefile(s)
625 	 */
626 	Arch_Init();
627 	Targ_Init();
628 	Suff_Init();
629 
630 	DEFAULT = NILGNODE;
631 	(void)time(&now);
632 
633 	/*
634 	 * Set up the .TARGETS variable to contain the list of targets to be
635 	 * created. If none specified, make the variable empty -- the parser
636 	 * will fill the thing in with the default or .MAIN target.
637 	 */
638 	if (!Lst_IsEmpty(create)) {
639 		LstNode ln;
640 
641 		for (ln = Lst_First(create); ln != NILLNODE;
642 		    ln = Lst_Succ(ln)) {
643 			char *name = (char *)Lst_Datum(ln);
644 
645 			Var_Append(".TARGETS", name, VAR_GLOBAL);
646 		}
647 	} else
648 		Var_Set(".TARGETS", "", VAR_GLOBAL);
649 
650 
651 	/*
652 	 * If no user-supplied system path was given (through the -m option)
653 	 * add the directories from the DEFSYSPATH (more than one may be given
654 	 * as dir1:...:dirn) to the system include path.
655 	 */
656 	if (Lst_IsEmpty(sysIncPath)) {
657 		for (start = syspath; *start != '\0'; start = cp) {
658 			for (cp = start; *cp != '\0' && *cp != ':'; cp++)
659 				continue;
660 			if (*cp == '\0') {
661 				Dir_AddDir(sysIncPath, start);
662 			} else {
663 				*cp++ = '\0';
664 				Dir_AddDir(sysIncPath, start);
665 			}
666 		}
667 	}
668 
669 	/*
670 	 * Read in the built-in rules first, followed by the specified
671 	 * makefile, if it was (makefile != (char *) NULL), or the default
672 	 * Makefile and makefile, in that order, if it wasn't.
673 	 */
674 	if (!noBuiltins) {
675 		LstNode ln;
676 
677 		sysMkPath = Lst_Init (FALSE);
678 		Dir_Expand (_PATH_DEFSYSMK, sysIncPath, sysMkPath);
679 		if (Lst_IsEmpty(sysMkPath))
680 			Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
681 		ln = Lst_Find(sysMkPath, (ClientData)NULL, ReadMakefile);
682 		if (ln != NILLNODE)
683 			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
684 	}
685 
686 	if (!Lst_IsEmpty(makefiles)) {
687 		LstNode ln;
688 
689 		ln = Lst_Find(makefiles, (ClientData)NULL, ReadMakefile);
690 		if (ln != NILLNODE)
691 			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
692 	} else if (!ReadMakefile("makefile", NULL))
693 		(void)ReadMakefile("Makefile", NULL);
694 
695 	(void)ReadMakefile(".depend", NULL);
696 
697 	Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
698 	if (p1)
699 	    free(p1);
700 
701 	/* Install all the flags into the MAKE envariable. */
702 	if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
703 #ifdef POSIX
704 		setenv("MAKEFLAGS", p, 1);
705 #else
706 		setenv("MAKE", p, 1);
707 #endif
708 	if (p1)
709 	    free(p1);
710 
711 	/*
712 	 * For compatibility, look at the directories in the VPATH variable
713 	 * and add them to the search path, if the variable is defined. The
714 	 * variable's value is in the same format as the PATH envariable, i.e.
715 	 * <directory>:<directory>:<directory>...
716 	 */
717 	if (Var_Exists("VPATH", VAR_CMD)) {
718 		char *vpath, *path, *cp, savec;
719 		/*
720 		 * GCC stores string constants in read-only memory, but
721 		 * Var_Subst will want to write this thing, so store it
722 		 * in an array
723 		 */
724 		static char VPATH[] = "${VPATH}";
725 
726 		vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
727 		path = vpath;
728 		do {
729 			/* skip to end of directory */
730 			for (cp = path; *cp != ':' && *cp != '\0'; cp++)
731 				continue;
732 			/* Save terminator character so know when to stop */
733 			savec = *cp;
734 			*cp = '\0';
735 			/* Add directory to search path */
736 			Dir_AddDir(dirSearchPath, path);
737 			*cp = savec;
738 			path = cp + 1;
739 		} while (savec == ':');
740 		(void)free((Address)vpath);
741 	}
742 
743 	/*
744 	 * Now that all search paths have been read for suffixes et al, it's
745 	 * time to add the default search path to their lists...
746 	 */
747 	Suff_DoPaths();
748 
749 	/* print the initial graph, if the user requested it */
750 	if (DEBUG(GRAPH1))
751 		Targ_PrintGraph(1);
752 
753 	/* print the values of any variables requested by the user */
754 	if (printVars) {
755 		LstNode ln;
756 
757 		for (ln = Lst_First(variables); ln != NILLNODE;
758 		    ln = Lst_Succ(ln)) {
759 			char *value = Var_Value((char *)Lst_Datum(ln),
760 					  VAR_GLOBAL, &p1);
761 
762 			printf("%s\n", value ? value : "");
763 			if (p1)
764 				free(p1);
765 		}
766 	}
767 
768 	/*
769 	 * Have now read the entire graph and need to make a list of targets
770 	 * to create. If none was given on the command line, we consult the
771 	 * parsing module to find the main target(s) to create.
772 	 */
773 	if (Lst_IsEmpty(create))
774 		targs = Parse_MainName();
775 	else
776 		targs = Targ_FindList(create, TARG_CREATE);
777 
778 	if (!compatMake && !printVars) {
779 		/*
780 		 * Initialize job module before traversing the graph, now that
781 		 * any .BEGIN and .END targets have been read.  This is done
782 		 * only if the -q flag wasn't given (to prevent the .BEGIN from
783 		 * being executed should it exist).
784 		 */
785 		if (!queryFlag) {
786 			if (maxLocal == -1)
787 				maxLocal = maxJobs;
788 			Job_Init(maxJobs, maxLocal);
789 			jobsRunning = TRUE;
790 		}
791 
792 		/* Traverse the graph, checking on all the targets */
793 		outOfDate = Make_Run(targs);
794 	} else if (!printVars) {
795 		/*
796 		 * Compat_Init will take care of creating all the targets as
797 		 * well as initializing the module.
798 		 */
799 		Compat_Run(targs);
800 	}
801 
802 	Lst_Destroy(targs, NOFREE);
803 	Lst_Destroy(variables, NOFREE);
804 	Lst_Destroy(makefiles, NOFREE);
805 	Lst_Destroy(create, (void (*) __P((ClientData))) free);
806 
807 	/* print the graph now it's been processed if the user requested it */
808 	if (DEBUG(GRAPH2))
809 		Targ_PrintGraph(2);
810 
811 	Suff_End();
812         Targ_End();
813 	Arch_End();
814 	str_end();
815 	Var_End();
816 	Parse_End();
817 	Dir_End();
818 
819 	if (queryFlag && outOfDate)
820 		return(1);
821 	else
822 		return(0);
823 }
824 
825 /*-
826  * ReadMakefile  --
827  *	Open and parse the given makefile.
828  *
829  * Results:
830  *	TRUE if ok. FALSE if couldn't open file.
831  *
832  * Side Effects:
833  *	lots
834  */
835 static Boolean
836 ReadMakefile(p, q)
837 	ClientData p, q;
838 {
839 	char *fname = p;		/* makefile to read */
840 	extern Lst parseIncPath;
841 	FILE *stream;
842 	char *name, path[MAXPATHLEN + 1];
843 
844 	if (!strcmp(fname, "-")) {
845 		Parse_File("(stdin)", stdin);
846 		Var_Set("MAKEFILE", "", VAR_GLOBAL);
847 	} else {
848 		if ((stream = fopen(fname, "r")) != NULL)
849 			goto found;
850 		/* if we've chdir'd, rebuild the path name */
851 		if (curdir != objdir && *fname != '/') {
852 			(void)sprintf(path, "%s/%s", curdir, fname);
853 			if ((stream = fopen(path, "r")) != NULL) {
854 				fname = path;
855 				goto found;
856 			}
857 		}
858 		/* look in -I and system include directories. */
859 		name = Dir_FindFile(fname, parseIncPath);
860 		if (!name)
861 			name = Dir_FindFile(fname, sysIncPath);
862 		if (!name || !(stream = fopen(name, "r")))
863 			return(FALSE);
864 		fname = name;
865 		/*
866 		 * set the MAKEFILE variable desired by System V fans -- the
867 		 * placement of the setting here means it gets set to the last
868 		 * makefile specified, as it is set by SysV make.
869 		 */
870 found:		Var_Set("MAKEFILE", fname, VAR_GLOBAL);
871 		Parse_File(fname, stream);
872 		(void)fclose(stream);
873 	}
874 	return(TRUE);
875 }
876 
877 /*-
878  * Cmd_Exec --
879  *	Execute the command in cmd, and return the output of that command
880  *	in a string.
881  *
882  * Results:
883  *	A string containing the output of the command, or the empty string
884  *	If err is not NULL, it contains the reason for the command failure
885  *
886  * Side Effects:
887  *	The string must be freed by the caller.
888  */
889 char *
890 Cmd_Exec(cmd, err)
891     char *cmd;
892     char **err;
893 {
894     char	*args[4];   	/* Args for invoking the shell */
895     int 	fds[2];	    	/* Pipe streams */
896     int 	cpid;	    	/* Child PID */
897     int 	pid;	    	/* PID from wait() */
898     char	*res;		/* result */
899     int		status;		/* command exit status */
900     Buffer	buf;		/* buffer to store the result */
901     char	*cp;
902     int		cc;
903 
904 
905     *err = NULL;
906 
907     /*
908      * Set up arguments for shell
909      */
910     args[0] = "sh";
911     args[1] = "-c";
912     args[2] = cmd;
913     args[3] = NULL;
914 
915     /*
916      * Open a pipe for fetching its output
917      */
918     if (pipe(fds) == -1) {
919 	*err = "Couldn't create pipe for \"%s\"";
920 	goto bad;
921     }
922 
923     /*
924      * Fork
925      */
926     switch (cpid = vfork()) {
927     case 0:
928 	/*
929 	 * Close input side of pipe
930 	 */
931 	(void) close(fds[0]);
932 
933 	/*
934 	 * Duplicate the output stream to the shell's output, then
935 	 * shut the extra thing down. Note we don't fetch the error
936 	 * stream...why not? Why?
937 	 */
938 	(void) dup2(fds[1], 1);
939 	(void) close(fds[1]);
940 
941 	(void) execv("/bin/sh", args);
942 	_exit(1);
943 	/*NOTREACHED*/
944 
945     case -1:
946 	*err = "Couldn't exec \"%s\"";
947 	goto bad;
948 
949     default:
950 	/*
951 	 * No need for the writing half
952 	 */
953 	(void) close(fds[1]);
954 
955 	buf = Buf_Init (MAKE_BSIZE);
956 
957 	do {
958 	    char   result[BUFSIZ];
959 	    cc = read(fds[0], result, sizeof(result));
960 	    if (cc > 0)
961 		Buf_AddBytes(buf, cc, (Byte *) result);
962 	}
963 	while (cc > 0 || (cc == -1 && errno == EINTR));
964 
965 	/*
966 	 * Close the input side of the pipe.
967 	 */
968 	(void) close(fds[0]);
969 
970 	/*
971 	 * Wait for the process to exit.
972 	 */
973 	while(((pid = wait(&status)) != cpid) && (pid >= 0))
974 	    continue;
975 
976 	res = (char *)Buf_GetAll (buf, &cc);
977 	Buf_Destroy (buf, FALSE);
978 
979 	if (cc == 0)
980 	    *err = "Couldn't read shell's output for \"%s\"";
981 
982 	if (status)
983 	    *err = "\"%s\" returned non-zero status";
984 
985 	/*
986 	 * Null-terminate the result, convert newlines to spaces and
987 	 * install it in the variable.
988 	 */
989 	res[cc] = '\0';
990 	cp = &res[cc] - 1;
991 
992 	if (*cp == '\n') {
993 	    /*
994 	     * A final newline is just stripped
995 	     */
996 	    *cp-- = '\0';
997 	}
998 	while (cp >= res) {
999 	    if (*cp == '\n') {
1000 		*cp = ' ';
1001 	    }
1002 	    cp--;
1003 	}
1004 	break;
1005     }
1006     return res;
1007 bad:
1008     res = emalloc(1);
1009     *res = '\0';
1010     return res;
1011 }
1012 
1013 /*-
1014  * Error --
1015  *	Print an error message given its format.
1016  *
1017  * Results:
1018  *	None.
1019  *
1020  * Side Effects:
1021  *	The message is printed.
1022  */
1023 /* VARARGS */
1024 void
1025 #ifdef __STDC__
1026 Error(char *fmt, ...)
1027 #else
1028 Error(va_alist)
1029 	va_dcl
1030 #endif
1031 {
1032 	va_list ap;
1033 #ifdef __STDC__
1034 	va_start(ap, fmt);
1035 #else
1036 	char *fmt;
1037 
1038 	va_start(ap);
1039 	fmt = va_arg(ap, char *);
1040 #endif
1041 	(void)vfprintf(stderr, fmt, ap);
1042 	va_end(ap);
1043 	(void)fprintf(stderr, "\n");
1044 	(void)fflush(stderr);
1045 }
1046 
1047 /*-
1048  * Fatal --
1049  *	Produce a Fatal error message. If jobs are running, waits for them
1050  *	to finish.
1051  *
1052  * Results:
1053  *	None
1054  *
1055  * Side Effects:
1056  *	The program exits
1057  */
1058 /* VARARGS */
1059 void
1060 #ifdef __STDC__
1061 Fatal(char *fmt, ...)
1062 #else
1063 Fatal(va_alist)
1064 	va_dcl
1065 #endif
1066 {
1067 	va_list ap;
1068 #ifdef __STDC__
1069 	va_start(ap, fmt);
1070 #else
1071 	char *fmt;
1072 
1073 	va_start(ap);
1074 	fmt = va_arg(ap, char *);
1075 #endif
1076 	if (jobsRunning)
1077 		Job_Wait();
1078 
1079 	(void)vfprintf(stderr, fmt, ap);
1080 	va_end(ap);
1081 	(void)fprintf(stderr, "\n");
1082 	(void)fflush(stderr);
1083 
1084 	if (DEBUG(GRAPH2))
1085 		Targ_PrintGraph(2);
1086 	exit(2);		/* Not 1 so -q can distinguish error */
1087 }
1088 
1089 /*
1090  * Punt --
1091  *	Major exception once jobs are being created. Kills all jobs, prints
1092  *	a message and exits.
1093  *
1094  * Results:
1095  *	None
1096  *
1097  * Side Effects:
1098  *	All children are killed indiscriminately and the program Lib_Exits
1099  */
1100 /* VARARGS */
1101 void
1102 #ifdef __STDC__
1103 Punt(char *fmt, ...)
1104 #else
1105 Punt(va_alist)
1106 	va_dcl
1107 #endif
1108 {
1109 	va_list ap;
1110 #ifdef __STDC__
1111 	va_start(ap, fmt);
1112 #else
1113 	char *fmt;
1114 
1115 	va_start(ap);
1116 	fmt = va_arg(ap, char *);
1117 #endif
1118 
1119 	(void)fprintf(stderr, "make: ");
1120 	(void)vfprintf(stderr, fmt, ap);
1121 	va_end(ap);
1122 	(void)fprintf(stderr, "\n");
1123 	(void)fflush(stderr);
1124 
1125 	DieHorribly();
1126 }
1127 
1128 /*-
1129  * DieHorribly --
1130  *	Exit without giving a message.
1131  *
1132  * Results:
1133  *	None
1134  *
1135  * Side Effects:
1136  *	A big one...
1137  */
1138 void
1139 DieHorribly()
1140 {
1141 	if (jobsRunning)
1142 		Job_AbortAll();
1143 	if (DEBUG(GRAPH2))
1144 		Targ_PrintGraph(2);
1145 	exit(2);		/* Not 1, so -q can distinguish error */
1146 }
1147 
1148 /*
1149  * Finish --
1150  *	Called when aborting due to errors in child shell to signal
1151  *	abnormal exit.
1152  *
1153  * Results:
1154  *	None
1155  *
1156  * Side Effects:
1157  *	The program exits
1158  */
1159 void
1160 Finish(errors)
1161 	int errors;	/* number of errors encountered in Make_Make */
1162 {
1163 	Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1164 }
1165 
1166 /*
1167  * emalloc --
1168  *	malloc, but die on error.
1169  */
1170 void *
1171 emalloc(len)
1172 	size_t len;
1173 {
1174 	void *p;
1175 
1176 	if ((p = malloc(len)) == NULL)
1177 		enomem();
1178 	return(p);
1179 }
1180 
1181 /*
1182  * estrdup --
1183  *	strdup, but die on error.
1184  */
1185 char *
1186 estrdup(str)
1187 	const char *str;
1188 {
1189 	char *p;
1190 
1191 	if ((p = strdup(str)) == NULL)
1192 		enomem();
1193 	return(p);
1194 }
1195 
1196 /*
1197  * erealloc --
1198  *	realloc, but die on error.
1199  */
1200 void *
1201 erealloc(ptr, size)
1202 	void *ptr;
1203 	size_t size;
1204 {
1205 	if ((ptr = realloc(ptr, size)) == NULL)
1206 		enomem();
1207 	return(ptr);
1208 }
1209 
1210 /*
1211  * enomem --
1212  *	die when out of memory.
1213  */
1214 void
1215 enomem()
1216 {
1217 	(void)fprintf(stderr, "make: %s.\n", strerror(errno));
1218 	exit(2);
1219 }
1220 
1221 /*
1222  * enunlink --
1223  *	Remove a file carefully, avoiding directories.
1224  */
1225 int
1226 eunlink(file)
1227 	const char *file;
1228 {
1229 	struct stat st;
1230 
1231 	if (lstat(file, &st) == -1)
1232 		return -1;
1233 
1234 	if (S_ISDIR(st.st_mode)) {
1235 		errno = EISDIR;
1236 		return -1;
1237 	}
1238 	return unlink(file);
1239 }
1240 
1241 /*
1242  * usage --
1243  *	exit with usage message
1244  */
1245 static void
1246 usage()
1247 {
1248 	(void)fprintf(stderr,
1249 "usage: make [-Beiknqrst] [-D variable] [-d flags] [-f makefile ]\n\
1250             [-I directory] [-j max_jobs] [-m directory] [-V variable]\n\
1251             [variable=value] [target ...]\n");
1252 	exit(2);
1253 }
1254 
1255 
1256 int
1257 PrintAddr(a, b)
1258     ClientData a;
1259     ClientData b;
1260 {
1261     printf("%lx ", (unsigned long) a);
1262     return b ? 0 : 0;
1263 }
1264