main.c revision 146134
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 146134 2005-05-12 11:58:39Z 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
58 *			Takes a line of arguments, breaks them and
59 *			treats them as if they were given when first
60 *			invoked. Used by the parse module to implement
61 *			the .MFLAGS target.
62 */
63
64#ifndef MACHINE
65#include <sys/utsname.h>
66#endif
67#include <sys/param.h>
68#include <sys/stat.h>
69#include <sys/sysctl.h>
70#include <sys/time.h>
71#include <sys/queue.h>
72#include <sys/resource.h>
73#include <sys/wait.h>
74#include <err.h>
75#include <errno.h>
76#include <signal.h>
77#include <stdlib.h>
78#include <string.h>
79#include <unistd.h>
80
81#include "arch.h"
82#include "buf.h"
83#include "config.h"
84#include "dir.h"
85#include "globals.h"
86#include "job.h"
87#include "make.h"
88#include "parse.h"
89#include "pathnames.h"
90#include "str.h"
91#include "suff.h"
92#include "targ.h"
93#include "util.h"
94#include "var.h"
95
96#define WANT_ENV_MKLVL	1
97#define	MKLVL_MAXVAL	500
98#define	MKLVL_ENVVAR	"__MKLVL__"
99
100#define	MAKEFLAGS	".MAKEFLAGS"
101
102extern char **environ;	/* XXX what header declares this variable? */
103
104/* Targets to be made */
105Lst create = Lst_Initializer(create);
106
107time_t		now;		/* Time at start of make */
108struct GNode	*DEFAULT;	/* .DEFAULT node */
109Boolean		allPrecious;	/* .PRECIOUS given on line by itself */
110uint32_t	warn_flags;	/* actual warning flags */
111uint32_t	warn_cmd;	/* command line warning flags */
112uint32_t	warn_nocmd;	/* command line no-warning flags */
113
114static Boolean	noBuiltins;	/* -r flag */
115
116/* ordered list of makefiles to read */
117static Lst makefiles = Lst_Initializer(makefiles);
118
119static Boolean	expandVars;	/* fully expand printed variables */
120
121/* list of variables to print */
122static Lst variables = Lst_Initializer(variables);
123
124static Boolean	forceJobs;      /* -j argument given */
125Boolean		compatMake;	/* -B argument */
126Boolean		debug;		/* -d flag */
127Boolean		noExecute;	/* -n flag */
128Boolean		keepgoing;	/* -k flag */
129Boolean		queryFlag;	/* -q flag */
130Boolean		touchFlag;	/* -t flag */
131Boolean		usePipes;	/* !-P flag */
132Boolean		ignoreErrors;	/* -i flag */
133Boolean		beSilent;	/* -s flag */
134Boolean		beVerbose;	/* -v flag */
135
136/* (-E) vars to override from env */
137Lst envFirstVars = Lst_Initializer(envFirstVars);
138
139Boolean		jobsRunning;	/* TRUE if the jobs might be running */
140
141char		*chdir_verify_path(const char *, char *);
142static int	ReadMakefile(const char *);
143static void	usage(void);
144
145static char	*curdir;	/* startup directory */
146static char	*objdir;	/* where we chdir'ed to */
147
148/**
149 * MFLAGS_append
150 *	Append a flag with an optional argument to MAKEFLAGS and MFLAGS
151 */
152static void
153MFLAGS_append(const char *flag, char *arg)
154{
155	char *str;
156
157	Var_Append(MAKEFLAGS, flag, VAR_GLOBAL);
158	if (arg != NULL) {
159		str = MAKEFLAGS_quote(arg);
160		Var_Append(MAKEFLAGS, str, VAR_GLOBAL);
161		free(str);
162	}
163
164	Var_Append("MFLAGS", flag, VAR_GLOBAL);
165	if (arg != NULL) {
166		str = MAKEFLAGS_quote(arg);
167		Var_Append("MFLAGS", str, VAR_GLOBAL);
168		free(str);
169	}
170}
171
172/**
173 * Main_ParseWarn
174 *
175 *	Handle argument to warning option.
176 */
177int
178Main_ParseWarn(const char *arg, int iscmd)
179{
180	int i, neg;
181
182	static const struct {
183		const char	*option;
184		uint32_t	flag;
185	} options[] = {
186		{ "dirsyntax",	WARN_DIRSYNTAX },
187		{ NULL,		0 }
188	};
189
190	neg = 0;
191	if (arg[0] == 'n' && arg[1] == 'o') {
192		neg = 1;
193		arg += 2;
194	}
195
196	for (i = 0; options[i].option != NULL; i++)
197		if (strcmp(arg, options[i].option) == 0)
198			break;
199
200	if (options[i].option == NULL)
201		/* unknown option */
202		return (-1);
203
204	if (iscmd) {
205		if (!neg) {
206			warn_cmd |= options[i].flag;
207			warn_nocmd &= ~options[i].flag;
208			warn_flags |= options[i].flag;
209		} else {
210			warn_nocmd |= options[i].flag;
211			warn_cmd &= ~options[i].flag;
212			warn_flags &= ~options[i].flag;
213		}
214	} else {
215		if (!neg) {
216			warn_flags |= (options[i].flag & ~warn_nocmd);
217		} else {
218			warn_flags &= ~(options[i].flag | warn_cmd);
219		}
220	}
221	return (0);
222}
223
224/**
225 * MainParseArgs
226 *	Parse a given argument vector. Called from main() and from
227 *	Main_ParseArgLine() when the .MAKEFLAGS target is used.
228 *
229 *	XXX: Deal with command line overriding .MAKEFLAGS in makefile
230 *
231 * Side Effects:
232 *	Various global and local flags will be set depending on the flags
233 *	given
234 */
235static void
236MainParseArgs(int argc, char **argv)
237{
238	int c;
239	Boolean	found_dd = FALSE;
240
241rearg:
242	optind = 1;	/* since we're called more than once */
243	optreset = 1;
244#define OPTFLAGS "ABC:D:E:I:PSV:Xd:ef:ij:km:nqrstvx:"
245	for (;;) {
246		if ((optind < argc) && strcmp(argv[optind], "--") == 0) {
247			found_dd = TRUE;
248		}
249		if ((c = getopt(argc, argv, OPTFLAGS)) == -1) {
250			break;
251		}
252		switch(c) {
253
254		case 'A':
255			arch_fatal = FALSE;
256			MFLAGS_append("-A", NULL);
257			break;
258		case 'C':
259			if (chdir(optarg) == -1)
260				err(1, "chdir %s", optarg);
261			break;
262		case 'D':
263			Var_Set(optarg, "1", VAR_GLOBAL);
264			MFLAGS_append("-D", optarg);
265			break;
266		case 'I':
267			Parse_AddIncludeDir(optarg);
268			MFLAGS_append("-I", optarg);
269			break;
270		case 'V':
271			Lst_AtEnd(&variables, estrdup(optarg));
272			MFLAGS_append("-V", optarg);
273			break;
274		case 'X':
275			expandVars = FALSE;
276			break;
277		case 'B':
278			compatMake = TRUE;
279			MFLAGS_append("-B", NULL);
280			unsetenv("MAKE_JOBS_FIFO");
281			break;
282		case 'P':
283			usePipes = FALSE;
284			MFLAGS_append("-P", NULL);
285			break;
286		case 'S':
287			keepgoing = FALSE;
288			MFLAGS_append("-S", NULL);
289			break;
290		case 'd': {
291			char *modules = optarg;
292
293			for (; *modules; ++modules)
294				switch (*modules) {
295				case 'A':
296					debug = ~0;
297					break;
298				case 'a':
299					debug |= DEBUG_ARCH;
300					break;
301				case 'c':
302					debug |= DEBUG_COND;
303					break;
304				case 'd':
305					debug |= DEBUG_DIR;
306					break;
307				case 'f':
308					debug |= DEBUG_FOR;
309					break;
310				case 'g':
311					if (modules[1] == '1') {
312						debug |= DEBUG_GRAPH1;
313						++modules;
314					}
315					else if (modules[1] == '2') {
316						debug |= DEBUG_GRAPH2;
317						++modules;
318					}
319					break;
320				case 'j':
321					debug |= DEBUG_JOB;
322					break;
323				case 'l':
324					debug |= DEBUG_LOUD;
325					break;
326				case 'm':
327					debug |= DEBUG_MAKE;
328					break;
329				case 's':
330					debug |= DEBUG_SUFF;
331					break;
332				case 't':
333					debug |= DEBUG_TARG;
334					break;
335				case 'v':
336					debug |= DEBUG_VAR;
337					break;
338				default:
339					warnx("illegal argument to d option "
340					    "-- %c", *modules);
341					usage();
342				}
343			MFLAGS_append("-d", optarg);
344			break;
345		}
346		case 'E':
347			Lst_AtEnd(&envFirstVars, estrdup(optarg));
348			MFLAGS_append("-E", optarg);
349			break;
350		case 'e':
351			checkEnvFirst = TRUE;
352			MFLAGS_append("-e", NULL);
353			break;
354		case 'f':
355			Lst_AtEnd(&makefiles, estrdup(optarg));
356			break;
357		case 'i':
358			ignoreErrors = TRUE;
359			MFLAGS_append("-i", NULL);
360			break;
361		case 'j': {
362			char *endptr;
363
364			forceJobs = TRUE;
365			maxJobs = strtol(optarg, &endptr, 10);
366			if (maxJobs <= 0 || *endptr != '\0') {
367				warnx("illegal number, -j argument -- %s",
368				    optarg);
369				usage();
370			}
371			MFLAGS_append("-j", optarg);
372			break;
373		}
374		case 'k':
375			keepgoing = TRUE;
376			MFLAGS_append("-k", NULL);
377			break;
378		case 'm':
379			Path_AddDir(&sysIncPath, optarg);
380			MFLAGS_append("-m", optarg);
381			break;
382		case 'n':
383			noExecute = TRUE;
384			MFLAGS_append("-n", NULL);
385			break;
386		case 'q':
387			queryFlag = TRUE;
388			/* Kind of nonsensical, wot? */
389			MFLAGS_append("-q", NULL);
390			break;
391		case 'r':
392			noBuiltins = TRUE;
393			MFLAGS_append("-r", NULL);
394			break;
395		case 's':
396			beSilent = TRUE;
397			MFLAGS_append("-s", NULL);
398			break;
399		case 't':
400			touchFlag = TRUE;
401			MFLAGS_append("-t", NULL);
402			break;
403		case 'v':
404			beVerbose = TRUE;
405			MFLAGS_append("-v", NULL);
406			break;
407		case 'x':
408			if (Main_ParseWarn(optarg, 1) != -1)
409				MFLAGS_append("-x", optarg);
410			break;
411
412		default:
413		case '?':
414			usage();
415		}
416	}
417	argv += optind;
418	argc -= optind;
419
420	oldVars = TRUE;
421
422	/*
423	 * Parse the rest of the arguments.
424	 *	o Check for variable assignments and perform them if so.
425	 *	o Check for more flags and restart getopt if so.
426	 *      o Anything else is taken to be a target and added
427	 *	  to the end of the "create" list.
428	 */
429	for (; *argv != NULL; ++argv, --argc) {
430		if (Parse_IsVar(*argv)) {
431			char *ptr = MAKEFLAGS_quote(*argv);
432
433			Var_Append(MAKEFLAGS, ptr, VAR_GLOBAL);
434			Parse_DoVar(*argv, VAR_CMD);
435			free(ptr);
436
437		} else if ((*argv)[0] == '-') {
438			if ((*argv)[1] == '\0') {
439				/*
440				 * (*argv) is a single dash, so we
441				 * just ignore it.
442				 */
443			} else if (found_dd) {
444				/*
445				 * Double dash has been found, ignore
446				 * any more options.  But what do we do
447				 * with it?  For now treat it like a target.
448				 */
449				Lst_AtEnd(&create, estrdup(*argv));
450			} else {
451				/*
452				 * (*argv) is a -flag, so backup argv and
453				 * argc.  getopt() expects options to start
454				 * in the 2nd position.
455				 */
456				argc++;
457				argv--;
458				goto rearg;
459			}
460
461		} else if ((*argv)[0] == '\0') {
462			Punt("illegal (null) argument.");
463
464		} else {
465			Lst_AtEnd(&create, estrdup(*argv));
466		}
467	}
468}
469
470/**
471 * Main_ParseArgLine
472 *  	Used by the parse module when a .MFLAGS or .MAKEFLAGS target
473 *	is encountered and by main() when reading the .MAKEFLAGS envariable.
474 *	Takes a line of arguments and breaks it into its
475 * 	component words and passes those words and the number of them to the
476 *	MainParseArgs function.
477 *	The line should have all its leading whitespace removed.
478 *
479 * Side Effects:
480 *	Only those that come from the various arguments.
481 */
482void
483Main_ParseArgLine(char *line, int mflags)
484{
485	char **argv;			/* Manufactured argument vector */
486	int argc;			/* Number of arguments in argv */
487
488	if (line == NULL)
489		return;
490	for (; *line == ' '; ++line)
491		continue;
492	if (!*line)
493		return;
494
495	if (mflags)
496		argv = MAKEFLAGS_break(line, &argc);
497	else
498		argv = brk_string(line, &argc, TRUE);
499
500	MainParseArgs(argc, argv);
501}
502
503char *
504chdir_verify_path(const char *path, char *obpath)
505{
506	struct stat sb;
507
508	if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
509		if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) {
510			warn("warning: %s", path);
511			return (NULL);
512		}
513		return (obpath);
514	}
515
516	return (NULL);
517}
518
519static void
520catch_child(int sig __unused)
521{
522}
523
524/*
525 * In lieu of a good way to prevent every possible looping in
526 * make(1), stop there from being more than MKLVL_MAXVAL processes forked
527 * by make(1), to prevent a forkbomb from happening, in a dumb and
528 * mechanical way.
529 */
530static void
531check_make_level(void)
532{
533#ifdef WANT_ENV_MKLVL
534	char	*value = getenv(MKLVL_ENVVAR);
535	int	level = (value == NULL) ? 0 : atoi(value);
536
537	if (level < 0) {
538		errc(2, EAGAIN, "Invalid value for recursion level (%d).",
539		    level);
540	} else if (level > MKLVL_MAXVAL) {
541		errc(2, EAGAIN, "Max recursion level (%d) exceeded.",
542		    MKLVL_MAXVAL);
543	} else {
544		char new_value[32];
545		sprintf(new_value, "%d", level + 1);
546		setenv(MKLVL_ENVVAR, new_value, 1);
547	}
548#endif /* WANT_ENV_MKLVL */
549}
550
551/**
552 * main
553 *	The main function, for obvious reasons. Initializes variables
554 *	and a few modules, then parses the arguments give it in the
555 *	environment and on the command line. Reads the system makefile
556 *	followed by either Makefile, makefile or the file given by the
557 *	-f argument. Sets the .MAKEFLAGS PMake variable based on all the
558 *	flags it has received by then uses either the Make or the Compat
559 *	module to create the initial list of targets.
560 *
561 * Results:
562 *	If -q was given, exits -1 if anything was out-of-date. Else it exits
563 *	0.
564 *
565 * Side Effects:
566 *	The program exits when done. Targets are created. etc. etc. etc.
567 */
568int
569main(int argc, char **argv)
570{
571	Boolean outOfDate = TRUE; 	/* FALSE if all targets up to date */
572	char *p, *p1, *pathp;
573	char *path;
574	char mdpath[MAXPATHLEN];
575	char obpath[MAXPATHLEN];
576	char cdpath[MAXPATHLEN];
577    	const char *machine = getenv("MACHINE");
578	const char *machine_arch = getenv("MACHINE_ARCH");
579	const char *machine_cpu = getenv("MACHINE_CPU");
580	char *cp = NULL, *start;
581
582	/* avoid faults on read-only strings */
583	static char syspath[] = PATH_DEFSYSPATH;
584
585	{
586	/*
587	 * Catch SIGCHLD so that we get kicked out of select() when we
588	 * need to look at a child.  This is only known to matter for the
589	 * -j case (perhaps without -P).
590	 *
591	 * XXX this is intentionally misplaced.
592	 */
593	struct sigaction sa;
594
595	sigemptyset(&sa.sa_mask);
596	sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
597	sa.sa_handler = catch_child;
598	sigaction(SIGCHLD, &sa, NULL);
599	}
600
601	check_make_level();
602
603#if DEFSHELL == 2
604	/*
605	 * Turn off ENV to make ksh happier.
606	 */
607	unsetenv("ENV");
608#endif
609
610#ifdef RLIMIT_NOFILE
611	/*
612	 * get rid of resource limit on file descriptors
613	 */
614	{
615		struct rlimit rl;
616		if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
617		    rl.rlim_cur != rl.rlim_max) {
618			rl.rlim_cur = rl.rlim_max;
619			setrlimit(RLIMIT_NOFILE, &rl);
620		}
621	}
622#endif
623
624	/*
625	 * PC-98 kernel sets the `i386' string to the utsname.machine and
626	 * it cannot be distinguished from IBM-PC by uname(3).  Therefore,
627	 * we check machine.ispc98 and adjust the machine variable before
628	 * using usname(3) below.
629	 * NOTE: machdep.ispc98 was defined on 1998/8/31. At that time,
630	 * __FreeBSD_version was defined as 300003. So, this check can
631	 * safely be done with any kernel with version > 300003.
632	 */
633	if (!machine) {
634		int	ispc98;
635		size_t	len;
636
637		len = sizeof(ispc98);
638		if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
639			if (ispc98)
640				machine = "pc98";
641		}
642	}
643
644	/*
645	 * Get the name of this type of MACHINE from utsname
646	 * so we can share an executable for similar machines.
647	 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
648	 *
649	 * Note that while MACHINE is decided at run-time,
650	 * MACHINE_ARCH is always known at compile time.
651	 */
652	if (!machine) {
653#ifndef MACHINE
654		static struct utsname utsname;
655
656		if (uname(&utsname) == -1)
657			err(2, "uname");
658		machine = utsname.machine;
659#else
660		machine = MACHINE;
661#endif
662	}
663
664	if (!machine_arch) {
665#ifndef MACHINE_ARCH
666		machine_arch = "unknown";
667#else
668		machine_arch = MACHINE_ARCH;
669#endif
670	}
671
672	/*
673	 * Set machine_cpu to the minumum supported CPU revision based
674	 * on the target architecture, if not already set.
675	 */
676	if (!machine_cpu) {
677		if (!strcmp(machine_arch, "i386"))
678			machine_cpu = "i386";
679		else if (!strcmp(machine_arch, "alpha"))
680			machine_cpu = "ev4";
681		else
682			machine_cpu = "unknown";
683	}
684
685	expandVars = TRUE;
686	beSilent = FALSE;		/* Print commands as executed */
687	ignoreErrors = FALSE;		/* Pay attention to non-zero returns */
688	noExecute = FALSE;		/* Execute all commands */
689	keepgoing = FALSE;		/* Stop on error */
690	allPrecious = FALSE;		/* Remove targets when interrupted */
691	queryFlag = FALSE;		/* This is not just a check-run */
692	noBuiltins = FALSE;		/* Read the built-in rules */
693	touchFlag = FALSE;		/* Actually update targets */
694	usePipes = TRUE;		/* Catch child output in pipes */
695	debug = 0;			/* No debug verbosity, please. */
696	jobsRunning = FALSE;
697
698	maxJobs = DEFMAXJOBS;
699	forceJobs = FALSE;              /* No -j flag */
700	compatMake = FALSE;		/* No compat mode */
701
702	/*
703	 * Initialize the parsing, directory and variable modules to prepare
704	 * for the reading of inclusion paths and variable settings on the
705	 * command line
706	 */
707	Dir_Init();		/* Initialize directory structures so -I flags
708				 * can be processed correctly */
709	Var_Init(environ);	/* As well as the lists of variables for
710				 * parsing arguments */
711        str_init();
712
713	/*
714	 * Initialize various variables.
715	 *	MAKE also gets this name, for compatibility
716	 *	.MAKEFLAGS gets set to the empty string just in case.
717	 *	MFLAGS also gets initialized empty, for compatibility.
718	 */
719	Var_Set("MAKE", argv[0], VAR_GLOBAL);
720	Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
721	Var_Set("MFLAGS", "", VAR_GLOBAL);
722	Var_Set("MACHINE", machine, VAR_GLOBAL);
723	Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
724	Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
725#ifdef MAKE_VERSION
726	Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
727#endif
728
729	/*
730	 * First snag things out of the MAKEFLAGS environment
731	 * variable.  Then parse the command line arguments.
732	 */
733	Main_ParseArgLine(getenv("MAKEFLAGS"), 1);
734
735	MainParseArgs(argc, argv);
736
737	/*
738	 * Find where we are...
739	 */
740	curdir = cdpath;
741	if (getcwd(curdir, MAXPATHLEN) == NULL)
742		err(2, NULL);
743
744	{
745	struct stat sa;
746
747	if (stat(curdir, &sa) == -1)
748	    err(2, "%s", curdir);
749	}
750
751	/*
752	 * The object directory location is determined using the
753	 * following order of preference:
754	 *
755	 *	1. MAKEOBJDIRPREFIX`cwd`
756	 *	2. MAKEOBJDIR
757	 *	3. PATH_OBJDIR.${MACHINE}
758	 *	4. PATH_OBJDIR
759	 *	5. PATH_OBJDIRPREFIX`cwd`
760	 *
761	 * If one of the first two fails, use the current directory.
762	 * If the remaining three all fail, use the current directory.
763	 *
764	 * Once things are initted,
765	 * have to add the original directory to the search path,
766	 * and modify the paths for the Makefiles apropriately.  The
767	 * current directory is also placed as a variable for make scripts.
768	 */
769	if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
770		if (!(path = getenv("MAKEOBJDIR"))) {
771			path = PATH_OBJDIR;
772			pathp = PATH_OBJDIRPREFIX;
773			snprintf(mdpath, MAXPATHLEN, "%s.%s",
774					path, machine);
775			if (!(objdir = chdir_verify_path(mdpath, obpath)))
776				if (!(objdir=chdir_verify_path(path, obpath))) {
777					snprintf(mdpath, MAXPATHLEN,
778							"%s%s", pathp, curdir);
779					if (!(objdir=chdir_verify_path(mdpath,
780								       obpath)))
781						objdir = curdir;
782				}
783		}
784		else if (!(objdir = chdir_verify_path(path, obpath)))
785			objdir = curdir;
786	}
787	else {
788		snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
789		if (!(objdir = chdir_verify_path(mdpath, obpath)))
790			objdir = curdir;
791	}
792	Dir_InitDot();		/* Initialize the "." directory */
793	if (objdir != curdir)
794		Path_AddDir(&dirSearchPath, curdir);
795	Var_Set(".ST_EXPORTVAR", "YES", VAR_GLOBAL);
796	Var_Set(".CURDIR", curdir, VAR_GLOBAL);
797	Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
798
799	if (getenv("MAKE_JOBS_FIFO") != NULL)
800		forceJobs = TRUE;
801	/*
802	 * Be compatible if user did not specify -j and did not explicitly
803	 * turned compatibility on
804	 */
805	if (!compatMake && !forceJobs)
806		compatMake = TRUE;
807
808	/*
809	 * Initialize target and suffix modules in preparation for
810	 * parsing the makefile(s)
811	 */
812	Targ_Init();
813	Suff_Init();
814
815	DEFAULT = NULL;
816	time(&now);
817
818	/*
819	 * Set up the .TARGETS variable to contain the list of targets to be
820	 * created. If none specified, make the variable empty -- the parser
821	 * will fill the thing in with the default or .MAIN target.
822	 */
823	if (!Lst_IsEmpty(&create)) {
824		LstNode *ln;
825
826		for (ln = Lst_First(&create); ln != NULL; ln = Lst_Succ(ln)) {
827			char *name = Lst_Datum(ln);
828
829			Var_Append(".TARGETS", name, VAR_GLOBAL);
830		}
831	} else
832		Var_Set(".TARGETS", "", VAR_GLOBAL);
833
834
835	/*
836	 * If no user-supplied system path was given (through the -m option)
837	 * add the directories from the DEFSYSPATH (more than one may be given
838	 * as dir1:...:dirn) to the system include path.
839	 */
840	if (TAILQ_EMPTY(&sysIncPath)) {
841		for (start = syspath; *start != '\0'; start = cp) {
842			for (cp = start; *cp != '\0' && *cp != ':'; cp++)
843				continue;
844			if (*cp == '\0') {
845				Path_AddDir(&sysIncPath, start);
846			} else {
847				*cp++ = '\0';
848				Path_AddDir(&sysIncPath, start);
849			}
850		}
851	}
852
853	/*
854	 * Read in the built-in rules first, followed by the specified
855	 * makefile, if it was (makefile != (char *) NULL), or the default
856	 * Makefile and makefile, in that order, if it wasn't.
857	 */
858	if (!noBuiltins) {
859		/* Path of sys.mk */
860		Lst sysMkPath = Lst_Initializer(sysMkPath);
861		LstNode *ln;
862		char	defsysmk[] = PATH_DEFSYSMK;
863
864		Path_Expand(defsysmk, &sysIncPath, &sysMkPath);
865		if (Lst_IsEmpty(&sysMkPath))
866			Fatal("make: no system rules (%s).", PATH_DEFSYSMK);
867		LST_FOREACH(ln, &sysMkPath) {
868			if (!ReadMakefile(Lst_Datum(ln)))
869				break;
870		}
871		if (ln != NULL)
872			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
873		Lst_Destroy(&sysMkPath, free);
874	}
875
876	if (!Lst_IsEmpty(&makefiles)) {
877		LstNode *ln;
878
879		LST_FOREACH(ln, &makefiles) {
880			if (!ReadMakefile(Lst_Datum(ln)))
881				break;
882		}
883		if (ln != NULL)
884			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
885	} else if (!ReadMakefile("BSDmakefile"))
886	    if (!ReadMakefile("makefile"))
887		ReadMakefile("Makefile");
888
889	ReadMakefile(".depend");
890
891	/* Install all the flags into the MAKE envariable. */
892	if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
893		setenv("MAKEFLAGS", p, 1);
894	free(p1);
895
896	/*
897	 * For compatibility, look at the directories in the VPATH variable
898	 * and add them to the search path, if the variable is defined. The
899	 * variable's value is in the same format as the PATH envariable, i.e.
900	 * <directory>:<directory>:<directory>...
901	 */
902	if (Var_Exists("VPATH", VAR_CMD)) {
903		/*
904		 * GCC stores string constants in read-only memory, but
905		 * Var_Subst will want to write this thing, so store it
906		 * in an array
907		 */
908		static char VPATH[] = "${VPATH}";
909		Buffer	*buf;
910		char	*vpath;
911		char	*ptr;
912		char	savec;
913
914		buf = Var_Subst(VPATH, VAR_CMD, FALSE);
915
916		vpath = Buf_Data(buf);
917		do {
918			/* skip to end of directory */
919			for (ptr = vpath; *ptr != ':' && *ptr != '\0'; ptr++)
920				;
921
922			/* Save terminator character so know when to stop */
923			savec = *ptr;
924			*ptr = '\0';
925
926			/* Add directory to search path */
927			Path_AddDir(&dirSearchPath, vpath);
928
929			vpath = ptr + 1;
930		} while (savec != '\0');
931
932		Buf_Destroy(buf, TRUE);
933	}
934
935	/*
936	 * Now that all search paths have been read for suffixes et al, it's
937	 * time to add the default search path to their lists...
938	 */
939	Suff_DoPaths();
940
941	/* print the initial graph, if the user requested it */
942	if (DEBUG(GRAPH1))
943		Targ_PrintGraph(1);
944
945	/* print the values of any variables requested by the user */
946	if (Lst_IsEmpty(&variables)) {
947		/*
948		 * Since the user has not requested that any variables
949		 * be printed, we can build targets.
950		 *
951		 * Have read the entire graph and need to make a list of targets
952		 * to create. If none was given on the command line, we consult
953		 * the parsing module to find the main target(s) to create.
954		 */
955		Lst targs = Lst_Initializer(targs);
956
957		if (Lst_IsEmpty(&create))
958			Parse_MainName(&targs);
959		else
960			Targ_FindList(&targs, &create, TARG_CREATE);
961
962		if (compatMake) {
963			/*
964			 * Compat_Init will take care of creating
965			 * all the targets as well as initializing
966			 * the module.
967			 */
968			Compat_Run(&targs);
969			outOfDate = 0;
970		} else {
971			/*
972			 * Initialize job module before traversing
973			 * the graph, now that any .BEGIN and .END
974			 * targets have been read.  This is done
975			 * only if the -q flag wasn't given (to
976			 * prevent the .BEGIN from being executed
977			 * should it exist).
978			 */
979			if (!queryFlag) {
980				Job_Init(maxJobs);
981				jobsRunning = TRUE;
982			}
983
984			/* Traverse the graph, checking on all the targets */
985			outOfDate = Make_Run(&targs);
986		}
987		Lst_Destroy(&targs, NOFREE);
988
989	} else {
990		/*
991		 * Print the values of any variables requested by
992		 * the user.
993		 */
994		LstNode		*n;
995		const char	*name;
996		char		*v;
997		char		*value;
998
999		LST_FOREACH(n, &variables) {
1000			name = Lst_Datum(n);
1001			if (expandVars) {
1002				v = emalloc(strlen(name) + 1 + 3);
1003				sprintf(v, "${%s}", name);
1004
1005				value = Buf_Peel(Var_Subst(v,
1006				    VAR_GLOBAL, FALSE));
1007				printf("%s\n", value);
1008
1009				free(v);
1010				free(value);
1011			} else {
1012				value = Var_Value(name, VAR_GLOBAL, &v);
1013				printf("%s\n", value != NULL ? value : "");
1014				if (v != NULL)
1015					free(v);
1016			}
1017		}
1018	}
1019
1020	Lst_Destroy(&variables, free);
1021	Lst_Destroy(&makefiles, free);
1022	Lst_Destroy(&create, free);
1023
1024	/* print the graph now it's been processed if the user requested it */
1025	if (DEBUG(GRAPH2))
1026		Targ_PrintGraph(2);
1027
1028	if (queryFlag && outOfDate)
1029		return (1);
1030	else
1031		return (0);
1032}
1033
1034/**
1035 * ReadMakefile
1036 *	Open and parse the given makefile.
1037 *
1038 * Results:
1039 *	TRUE if ok. FALSE if couldn't open file.
1040 *
1041 * Side Effects:
1042 *	lots
1043 */
1044static Boolean
1045ReadMakefile(const char *p)
1046{
1047	char *fname;			/* makefile to read */
1048	FILE *stream;
1049	char *name, path[MAXPATHLEN];
1050	char *MAKEFILE;
1051	int setMAKEFILE;
1052
1053	/* XXX - remove this once constification is done */
1054	fname = estrdup(p);
1055
1056	if (!strcmp(fname, "-")) {
1057		Parse_File("(stdin)", stdin);
1058		Var_Set("MAKEFILE", "", VAR_GLOBAL);
1059	} else {
1060		setMAKEFILE = strcmp(fname, ".depend");
1061
1062		/* if we've chdir'd, rebuild the path name */
1063		if (curdir != objdir && *fname != '/') {
1064			snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
1065			/*
1066			 * XXX The realpath stuff breaks relative includes
1067			 * XXX in some cases.   The problem likely is in
1068			 * XXX parse.c where it does special things in
1069			 * XXX ParseDoInclude if the file is relateive
1070			 * XXX or absolute and not a system file.  There
1071			 * XXX it assumes that if the current file that's
1072			 * XXX being included is absolute, that any files
1073			 * XXX that it includes shouldn't do the -I path
1074			 * XXX stuff, which is inconsistant with historical
1075			 * XXX behavior.  However, I can't pentrate the mists
1076			 * XXX further, so I'm putting this workaround in
1077			 * XXX here until such time as the underlying bug
1078			 * XXX can be fixed.
1079			 */
1080#if THIS_BREAKS_THINGS
1081			if (realpath(path, path) != NULL &&
1082			    (stream = fopen(path, "r")) != NULL) {
1083				MAKEFILE = fname;
1084				fname = path;
1085				goto found;
1086			}
1087		} else if (realpath(fname, path) != NULL) {
1088			MAKEFILE = fname;
1089			fname = path;
1090			if ((stream = fopen(fname, "r")) != NULL)
1091				goto found;
1092		}
1093#else
1094			if ((stream = fopen(path, "r")) != NULL) {
1095				MAKEFILE = fname;
1096				fname = path;
1097				goto found;
1098			}
1099		} else {
1100			MAKEFILE = fname;
1101			if ((stream = fopen(fname, "r")) != NULL)
1102				goto found;
1103		}
1104#endif
1105		/* look in -I and system include directories. */
1106		name = Path_FindFile(fname, &parseIncPath);
1107		if (!name)
1108			name = Path_FindFile(fname, &sysIncPath);
1109		if (!name || !(stream = fopen(name, "r")))
1110			return (FALSE);
1111		MAKEFILE = fname = name;
1112		/*
1113		 * set the MAKEFILE variable desired by System V fans -- the
1114		 * placement of the setting here means it gets set to the last
1115		 * makefile specified, as it is set by SysV make.
1116		 */
1117found:
1118		if (setMAKEFILE)
1119			Var_Set("MAKEFILE", MAKEFILE, VAR_GLOBAL);
1120		Parse_File(fname, stream);
1121		fclose(stream);
1122	}
1123	return (TRUE);
1124}
1125
1126/*
1127 * usage --
1128 *	exit with usage message
1129 */
1130static void
1131usage(void)
1132{
1133	fprintf(stderr, "%s\n%s\n%s\n%s\n",
1134"usage: make [-ABPSXeiknqrstv] [-C directory] [-D variable] [-d flags]",
1135"            [-E variable] [-f makefile] [-I directory] [-j max_jobs]",
1136"            [-m directory] [-V variable] [variable=value] [-x warn_flag]",
1137"            [target ...]");
1138	exit(2);
1139}
1140