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