main.c revision 75973
1189251Ssam/*
2189251Ssam * Copyright (c) 1988, 1989, 1990, 1993
3189251Ssam *	The Regents of the University of California.  All rights reserved.
4189251Ssam * Copyright (c) 1989 by Berkeley Softworks
5189251Ssam * All rights reserved.
6189251Ssam *
7189251Ssam * This code is derived from software contributed to Berkeley by
8189251Ssam * Adam de Boor.
9189251Ssam *
10189251Ssam * Redistribution and use in source and binary forms, with or without
11189251Ssam * modification, are permitted provided that the following conditions
12189251Ssam * are met:
13189251Ssam * 1. Redistributions of source code must retain the above copyright
14189251Ssam *    notice, this list of conditions and the following disclaimer.
15189251Ssam * 2. Redistributions in binary form must reproduce the above copyright
16189251Ssam *    notice, this list of conditions and the following disclaimer in the
17189251Ssam *    documentation and/or other materials provided with the distribution.
18189251Ssam * 3. All advertising materials mentioning features or use of this software
19189251Ssam *    must display the following acknowledgement:
20189251Ssam *	This product includes software developed by the University of
21189251Ssam *	California, Berkeley and its contributors.
22189251Ssam * 4. Neither the name of the University nor the names of its contributors
23189251Ssam *    may be used to endorse or promote products derived from this software
24189251Ssam *    without specific prior written permission.
25189251Ssam *
26189251Ssam * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27189251Ssam * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28189251Ssam * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29189251Ssam * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30189251Ssam * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31189251Ssam * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32189251Ssam * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33189251Ssam * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34189251Ssam * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35189251Ssam * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36189251Ssam * SUCH DAMAGE.
37189251Ssam *
38189251Ssam * @(#)main.c      8.3 (Berkeley) 3/19/94
39189251Ssam */
40189251Ssam
41189251Ssam#ifndef lint
42189251Ssam#include <sys/cdefs.h>
43189251Ssam__COPYRIGHT("@(#) Copyright (c) 1988, 1989, 1990, 1993  The Regents of the University of California.  All rights reserved.");
44189251Ssam__RCSID("$FreeBSD: head/usr.bin/make/main.c 75973 2001-04-25 14:22:38Z ru $");
45189251Ssam#endif /* not lint */
46189251Ssam
47189251Ssam/*-
48189251Ssam * main.c --
49189251Ssam *	The main file for this entire program. Exit routines etc
50189251Ssam *	reside here.
51189251Ssam *
52189251Ssam * Utility functions defined in this file:
53189251Ssam *	Main_ParseArgLine	Takes a line of arguments, breaks them and
54189251Ssam *				treats them as if they were given when first
55189251Ssam *				invoked. Used by the parse module to implement
56189251Ssam *				the .MFLAGS target.
57189251Ssam *
58189251Ssam *	Error			Print a tagged error message. The global
59189251Ssam *				MAKE variable must have been defined. This
60189251Ssam *				takes a format string and two optional
61189251Ssam *				arguments for it.
62189251Ssam *
63189251Ssam *	Fatal			Print an error message and exit. Also takes
64189251Ssam *				a format string and two arguments.
65189251Ssam *
66189251Ssam *	Punt			Aborts all jobs and exits with a message. Also
67189251Ssam *				takes a format string and two arguments.
68189251Ssam *
69189251Ssam *	Finish			Finish things up by printing the number of
70189251Ssam *				errors which occured, as passed to it, and
71189251Ssam *				exiting.
72189251Ssam */
73189251Ssam
74189251Ssam#include <sys/types.h>
75189251Ssam#include <sys/time.h>
76189251Ssam#include <sys/param.h>
77189251Ssam#include <sys/resource.h>
78189251Ssam#include <sys/signal.h>
79189251Ssam#include <sys/stat.h>
80189251Ssam#if defined(__i386__)
81189251Ssam#include <sys/sysctl.h>
82189251Ssam#endif
83189251Ssam#ifndef MACHINE
84189251Ssam#include <sys/utsname.h>
85189251Ssam#endif
86189251Ssam#include <sys/wait.h>
87189251Ssam#include <err.h>
88189251Ssam#include <stdlib.h>
89189251Ssam#include <errno.h>
90189251Ssam#include <fcntl.h>
91189251Ssam#include <stdio.h>
92189251Ssam#include <sysexits.h>
93189251Ssam#ifdef __STDC__
94189251Ssam#include <stdarg.h>
95189251Ssam#else
96189251Ssam#include <varargs.h>
97189251Ssam#endif
98189251Ssam#include <unistd.h>
99189251Ssam#include "make.h"
100189251Ssam#include "hash.h"
101189251Ssam#include "dir.h"
102189251Ssam#include "job.h"
103189251Ssam#include "pathnames.h"
104189251Ssam
105189251Ssam#ifndef	DEFMAXLOCAL
106189251Ssam#define	DEFMAXLOCAL DEFMAXJOBS
107189251Ssam#endif	/* DEFMAXLOCAL */
108189251Ssam
109189251Ssam#define	MAKEFLAGS	".MAKEFLAGS"
110189251Ssam
111189251SsamLst			create;		/* Targets to be made */
112189251Ssamtime_t			now;		/* Time at start of make */
113189251SsamGNode			*DEFAULT;	/* .DEFAULT node */
114189251SsamBoolean			allPrecious;	/* .PRECIOUS given on line by itself */
115189251Ssam
116189251Ssamstatic Boolean		noBuiltins;	/* -r flag */
117189251Ssamstatic Lst		makefiles;	/* ordered list of makefiles to read */
118189251Ssamstatic Boolean		printVars;	/* print value of one or more vars */
119189251Ssamstatic Boolean		expandVars;	/* fully expand printed variables */
120189251Ssamstatic Lst		variables;	/* list of variables to print */
121189251Ssamint			maxJobs;	/* -j argument */
122189251Ssamstatic Boolean          forceJobs;      /* -j argument given */
123189251Ssamstatic int		maxLocal;	/* -L argument */
124189251SsamBoolean			compatMake;	/* -B argument */
125189251SsamBoolean			debug;		/* -d flag */
126189251SsamBoolean			noExecute;	/* -n flag */
127189251SsamBoolean			keepgoing;	/* -k flag */
128189251SsamBoolean			queryFlag;	/* -q flag */
129189251SsamBoolean			touchFlag;	/* -t flag */
130189251SsamBoolean			usePipes;	/* !-P flag */
131189251SsamBoolean			ignoreErrors;	/* -i flag */
132189251SsamBoolean			beSilent;	/* -s flag */
133189251SsamBoolean			beVerbose;	/* -v flag */
134209158SrpauloBoolean			oldVars;	/* variable substitution style */
135189251SsamBoolean			checkEnvFirst;	/* -e flag */
136189251SsamLst			envFirstVars;	/* (-E) vars to override from env */
137189251Ssamstatic Boolean		jobsRunning;	/* TRUE if the jobs might be running */
138189251Ssam
139189251Ssamstatic void		MainParseArgs __P((int, char **));
140189251Ssamchar *			chdir_verify_path __P((char *, char *));
141189251Ssamstatic int		ReadMakefile __P((void *, void *));
142189251Ssamstatic void		usage __P((void));
143189251Ssam
144189251Ssamstatic char *curdir;			/* startup directory */
145189251Ssamstatic char *objdir;			/* where we chdir'ed to */
146189251Ssam
147189251Ssam/*-
148189251Ssam * MainParseArgs --
149189251Ssam *	Parse a given argument vector. Called from main() and from
150189251Ssam *	Main_ParseArgLine() when the .MAKEFLAGS target is used.
151189251Ssam *
152189251Ssam *	XXX: Deal with command line overriding .MAKEFLAGS in makefile
153189251Ssam *
154189251Ssam * Results:
155189251Ssam *	None
156189251Ssam *
157189251Ssam * Side Effects:
158189251Ssam *	Various global and local flags will be set depending on the flags
159189251Ssam *	given
160189251Ssam */
161189251Ssamstatic void
162189251SsamMainParseArgs(argc, argv)
163189251Ssam	int argc;
164189251Ssam	char **argv;
165189251Ssam{
166189251Ssam	char *p;
167189251Ssam	int c;
168189251Ssam
169189251Ssam	optind = 1;	/* since we're called more than once */
170189251Ssam#ifdef REMOTE
171189251Ssam# define OPTFLAGS "BD:E:I:L:PSV:Xd:ef:ij:km:nqrstv"
172189251Ssam#else
173189251Ssam# define OPTFLAGS "BD:E:I:PSV:Xd:ef:ij:km:nqrstv"
174189251Ssam#endif
175189251Ssamrearg:	while((c = getopt(argc, argv, OPTFLAGS)) != -1) {
176189251Ssam		switch(c) {
177189251Ssam		case 'D':
178189251Ssam			Var_Set(optarg, "1", VAR_GLOBAL);
179189251Ssam			Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
180189251Ssam			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
181189251Ssam			break;
182189251Ssam		case 'I':
183189251Ssam			Parse_AddIncludeDir(optarg);
184189251Ssam			Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
185189251Ssam			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
186189251Ssam			break;
187189251Ssam		case 'V':
188189251Ssam			printVars = TRUE;
189189251Ssam			(void)Lst_AtEnd(variables, (void *)optarg);
190189251Ssam			Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
191189251Ssam			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
192189251Ssam			break;
193189251Ssam		case 'X':
194189251Ssam			expandVars = FALSE;
195189251Ssam			break;
196189251Ssam		case 'B':
197189251Ssam			compatMake = TRUE;
198189251Ssam			Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
199189251Ssam			break;
200189251Ssam#ifdef REMOTE
201189251Ssam		case 'L': {
202189251Ssam			char *endptr;
203189251Ssam
204189251Ssam			maxLocal = strtol(optarg, &endptr, 10);
205189251Ssam			if (maxLocal < 0 || *endptr != '\0') {
206189251Ssam				warnx("illegal number, -L argument -- %s",
207189251Ssam				    optarg);
208189251Ssam				usage();
209189251Ssam			}
210189251Ssam			Var_Append(MAKEFLAGS, "-L", VAR_GLOBAL);
211189251Ssam			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
212189251Ssam			break;
213189251Ssam		}
214189251Ssam#endif
215189251Ssam		case 'P':
216189251Ssam			usePipes = FALSE;
217189251Ssam			Var_Append(MAKEFLAGS, "-P", VAR_GLOBAL);
218189251Ssam			break;
219189251Ssam		case 'S':
220189251Ssam			keepgoing = FALSE;
221189251Ssam			Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
222189251Ssam			break;
223189251Ssam		case 'd': {
224189251Ssam			char *modules = optarg;
225189251Ssam
226189251Ssam			for (; *modules; ++modules)
227189251Ssam				switch (*modules) {
228189251Ssam				case 'A':
229189251Ssam					debug = ~0;
230189251Ssam					break;
231189251Ssam				case 'a':
232189251Ssam					debug |= DEBUG_ARCH;
233189251Ssam					break;
234189251Ssam				case 'c':
235189251Ssam					debug |= DEBUG_COND;
236189251Ssam					break;
237189251Ssam				case 'd':
238189251Ssam					debug |= DEBUG_DIR;
239189251Ssam					break;
240189251Ssam				case 'f':
241189251Ssam					debug |= DEBUG_FOR;
242189251Ssam					break;
243189251Ssam				case 'g':
244189251Ssam					if (modules[1] == '1') {
245189251Ssam						debug |= DEBUG_GRAPH1;
246189251Ssam						++modules;
247189251Ssam					}
248189251Ssam					else if (modules[1] == '2') {
249189251Ssam						debug |= DEBUG_GRAPH2;
250189251Ssam						++modules;
251189251Ssam					}
252189251Ssam					break;
253189251Ssam				case 'j':
254189251Ssam					debug |= DEBUG_JOB;
255189251Ssam					break;
256189251Ssam				case 'l':
257189251Ssam					debug |= DEBUG_LOUD;
258189251Ssam					break;
259189251Ssam				case 'm':
260189251Ssam					debug |= DEBUG_MAKE;
261189251Ssam					break;
262189251Ssam				case 's':
263189251Ssam					debug |= DEBUG_SUFF;
264189251Ssam					break;
265189251Ssam				case 't':
266189251Ssam					debug |= DEBUG_TARG;
267189251Ssam					break;
268189251Ssam				case 'v':
269189251Ssam					debug |= DEBUG_VAR;
270189251Ssam					break;
271189251Ssam				default:
272189251Ssam					warnx("illegal argument to d option -- %c", *modules);
273189251Ssam					usage();
274189251Ssam				}
275189251Ssam			Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
276189251Ssam			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
277189251Ssam			break;
278189251Ssam		}
279189251Ssam		case 'E':
280189251Ssam			p = malloc(strlen(optarg) + 1);
281189251Ssam			if (!p)
282189251Ssam				Punt("make: cannot allocate memory.");
283189251Ssam			(void)strcpy(p, optarg);
284189251Ssam			(void)Lst_AtEnd(envFirstVars, (void *)p);
285189251Ssam			Var_Append(MAKEFLAGS, "-E", VAR_GLOBAL);
286189251Ssam			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
287189251Ssam			break;
288189251Ssam		case 'e':
289189251Ssam			checkEnvFirst = TRUE;
290189251Ssam			Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
291189251Ssam			break;
292189251Ssam		case 'f':
293189251Ssam			(void)Lst_AtEnd(makefiles, (void *)optarg);
294189251Ssam			break;
295189251Ssam		case 'i':
296189251Ssam			ignoreErrors = TRUE;
297189251Ssam			Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
298189251Ssam			break;
299189251Ssam		case 'j': {
300189251Ssam			char *endptr;
301189251Ssam
302189251Ssam			forceJobs = TRUE;
303189251Ssam			maxJobs = strtol(optarg, &endptr, 10);
304189251Ssam			if (maxJobs <= 0 || *endptr != '\0') {
305189251Ssam				warnx("illegal number, -j argument -- %s",
306189251Ssam				    optarg);
307189251Ssam				usage();
308189251Ssam			}
309189251Ssam#ifndef REMOTE
310189251Ssam			maxLocal = maxJobs;
311189251Ssam#endif
312189251Ssam			Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
313189251Ssam			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
314189251Ssam			break;
315189251Ssam		}
316189251Ssam		case 'k':
317189251Ssam			keepgoing = TRUE;
318189251Ssam			Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
319189251Ssam			break;
320189251Ssam		case 'm':
321189251Ssam			Dir_AddDir(sysIncPath, optarg);
322189251Ssam			Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
323189251Ssam			Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
324189251Ssam			break;
325189251Ssam		case 'n':
326189251Ssam			noExecute = TRUE;
327189251Ssam			Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
328189251Ssam			break;
329189251Ssam		case 'q':
330189251Ssam			queryFlag = TRUE;
331189251Ssam			/* Kind of nonsensical, wot? */
332189251Ssam			Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
333189251Ssam			break;
334189251Ssam		case 'r':
335189251Ssam			noBuiltins = TRUE;
336189251Ssam			Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
337189251Ssam			break;
338189251Ssam		case 's':
339189251Ssam			beSilent = TRUE;
340189251Ssam			Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
341189251Ssam			break;
342189251Ssam		case 't':
343189251Ssam			touchFlag = TRUE;
344189251Ssam			Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
345189251Ssam			break;
346189251Ssam		case 'v':
347189251Ssam			beVerbose = TRUE;
348189251Ssam			Var_Append(MAKEFLAGS, "-v", VAR_GLOBAL);
349189251Ssam			break;
350189251Ssam		default:
351189251Ssam		case '?':
352189251Ssam			usage();
353189251Ssam		}
354189251Ssam	}
355189251Ssam
356189251Ssam	oldVars = TRUE;
357189251Ssam
358189251Ssam	/*
359189251Ssam	 * See if the rest of the arguments are variable assignments and
360189251Ssam	 * perform them if so. Else take them to be targets and stuff them
361189251Ssam	 * on the end of the "create" list.
362189251Ssam	 */
363189251Ssam	for (argv += optind, argc -= optind; *argv; ++argv, --argc)
364189251Ssam		if (Parse_IsVar(*argv))
365189251Ssam			Parse_DoVar(*argv, VAR_CMD);
366189251Ssam		else {
367189251Ssam			if (!**argv)
368189251Ssam				Punt("illegal (null) argument.");
369189251Ssam			if (**argv == '-') {
370189251Ssam				if ((*argv)[1])
371189251Ssam					optind = 0;     /* -flag... */
372189251Ssam				else
373189251Ssam					optind = 1;     /* - */
374189251Ssam				goto rearg;
375189251Ssam			}
376189251Ssam			(void)Lst_AtEnd(create, (void *)estrdup(*argv));
377189251Ssam		}
378189251Ssam}
379189251Ssam
380189251Ssam/*-
381189251Ssam * Main_ParseArgLine --
382189251Ssam *  	Used by the parse module when a .MFLAGS or .MAKEFLAGS target
383189251Ssam *	is encountered and by main() when reading the .MAKEFLAGS envariable.
384189251Ssam *	Takes a line of arguments and breaks it into its
385189251Ssam * 	component words and passes those words and the number of them to the
386189251Ssam *	MainParseArgs function.
387189251Ssam *	The line should have all its leading whitespace removed.
388189251Ssam *
389189251Ssam * Results:
390189251Ssam *	None
391189251Ssam *
392189251Ssam * Side Effects:
393189251Ssam *	Only those that come from the various arguments.
394189251Ssam */
395189251Ssamvoid
396189251SsamMain_ParseArgLine(line)
397189251Ssam	char *line;			/* Line to fracture */
398189251Ssam{
399189251Ssam	char **argv;			/* Manufactured argument vector */
400189251Ssam	int argc;			/* Number of arguments in argv */
401189251Ssam
402189251Ssam	if (line == NULL)
403189251Ssam		return;
404189251Ssam	for (; *line == ' '; ++line)
405189251Ssam		continue;
406189251Ssam	if (!*line)
407189251Ssam		return;
408189251Ssam
409189251Ssam	argv = brk_string(line, &argc, TRUE);
410189251Ssam	MainParseArgs(argc, argv);
411189251Ssam}
412189251Ssam
413189251Ssamchar *
414189251Ssamchdir_verify_path(path, obpath)
415189251Ssam	char *path;
416189251Ssam	char *obpath;
417189251Ssam{
418189251Ssam	struct stat sb;
419189251Ssam
420189251Ssam	if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
421189251Ssam		if (chdir(path) == -1 || getcwd(obpath, MAXPATHLEN) == NULL) {
422189251Ssam			warn("warning: %s", path);
423189251Ssam			return 0;
424189251Ssam		}
425189251Ssam		return obpath;
426189251Ssam	}
427189251Ssam
428189251Ssam	return 0;
429189251Ssam}
430189251Ssam
431189251Ssam
432189251Ssam/*-
433189251Ssam * main --
434189251Ssam *	The main function, for obvious reasons. Initializes variables
435189251Ssam *	and a few modules, then parses the arguments give it in the
436189251Ssam *	environment and on the command line. Reads the system makefile
437189251Ssam *	followed by either Makefile, makefile or the file given by the
438189251Ssam *	-f argument. Sets the .MAKEFLAGS PMake variable based on all the
439189251Ssam *	flags it has received by then uses either the Make or the Compat
440189251Ssam *	module to create the initial list of targets.
441189251Ssam *
442189251Ssam * Results:
443189251Ssam *	If -q was given, exits -1 if anything was out-of-date. Else it exits
444189251Ssam *	0.
445189251Ssam *
446189251Ssam * Side Effects:
447189251Ssam *	The program exits when done. Targets are created. etc. etc. etc.
448189251Ssam */
449189251Ssamint
450189251Ssammain(argc, argv)
451189251Ssam	int argc;
452189251Ssam	char **argv;
453189251Ssam{
454189251Ssam	Lst targs;	/* target nodes to create -- passed to Make_Init */
455189251Ssam	Boolean outOfDate = TRUE; 	/* FALSE if all targets up to date */
456189251Ssam	struct stat sa;
457189251Ssam	char *p, *p1, *path, *pathp;
458189251Ssam#ifdef WANT_ENV_PWD
459189251Ssam	struct stat sb;
460189251Ssam	char *pwd;
461189251Ssam#endif
462189251Ssam	char mdpath[MAXPATHLEN];
463189251Ssam	char obpath[MAXPATHLEN];
464189251Ssam	char cdpath[MAXPATHLEN];
465189251Ssam    	char *machine = getenv("MACHINE");
466189251Ssam	char *machine_arch = getenv("MACHINE_ARCH");
467189251Ssam	char *machine_cpu = getenv("MACHINE_CPU");
468189251Ssam	Lst sysMkPath;			/* Path of sys.mk */
469189251Ssam	char *cp = NULL, *start;
470189251Ssam					/* avoid faults on read-only strings */
471189251Ssam	static char syspath[] = _PATH_DEFSYSPATH;
472189251Ssam
473189251Ssam#if DEFSHELL == 2
474189251Ssam	/*
475189251Ssam	 * Turn off ENV to make ksh happier.
476189251Ssam	 */
477189251Ssam	unsetenv("ENV");
478189251Ssam#endif
479189251Ssam
480189251Ssam#ifdef RLIMIT_NOFILE
481189251Ssam	/*
482189251Ssam	 * get rid of resource limit on file descriptors
483189251Ssam	 */
484189251Ssam	{
485189251Ssam		struct rlimit rl;
486189251Ssam		if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
487189251Ssam		    rl.rlim_cur != rl.rlim_max) {
488189251Ssam			rl.rlim_cur = rl.rlim_max;
489189251Ssam			(void) setrlimit(RLIMIT_NOFILE, &rl);
490189251Ssam		}
491189251Ssam	}
492189251Ssam#endif
493189251Ssam	/*
494189251Ssam	 * Find where we are and take care of PWD for the automounter...
495189251Ssam	 * All this code is so that we know where we are when we start up
496189251Ssam	 * on a different machine with pmake.
497189251Ssam	 */
498189251Ssam	curdir = cdpath;
499189251Ssam	if (getcwd(curdir, MAXPATHLEN) == NULL)
500189251Ssam		err(2, NULL);
501189251Ssam
502189251Ssam	if (stat(curdir, &sa) == -1)
503189251Ssam	    err(2, "%s", curdir);
504189251Ssam
505189251Ssam#ifdef WANT_ENV_PWD
506189251Ssam	if ((pwd = getenv("PWD")) != NULL) {
507189251Ssam	    if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
508189251Ssam		sa.st_dev == sb.st_dev)
509189251Ssam		(void) strcpy(curdir, pwd);
510189251Ssam	}
511189251Ssam#endif
512189251Ssam
513189251Ssam#if defined(__i386__) && defined(__FreeBSD_version) && \
514189251Ssam    __FreeBSD_version > 300003
515189251Ssam	/*
516189251Ssam	 * PC-98 kernel sets the `i386' string to the utsname.machine and
517189251Ssam	 * it cannot be distinguished from IBM-PC by uname(3).  Therefore,
518189251Ssam	 * we check machine.ispc98 and adjust the machine variable before
519189251Ssam	 * using usname(3) below.
520189251Ssam	 * NOTE: machdep.ispc98 was defined on 1998/8/31. At that time,
521189251Ssam	 * __FreeBSD_version was defined as 300003. So, this check can
522189251Ssam	 * safely be done with any kernel with version > 300003.
523189251Ssam	 */
524189251Ssam	if (!machine) {
525189251Ssam		int	ispc98;
526189251Ssam		size_t	len;
527189251Ssam
528189251Ssam		len = sizeof(ispc98);
529189251Ssam		if (!sysctlbyname("machdep.ispc98", &ispc98, &len, NULL, 0)) {
530189251Ssam			if (ispc98)
531189251Ssam				machine = "pc98";
532189251Ssam		}
533189251Ssam	}
534189251Ssam#endif
535189251Ssam
536189251Ssam	/*
537189251Ssam	 * Get the name of this type of MACHINE from utsname
538189251Ssam	 * so we can share an executable for similar machines.
539189251Ssam	 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
540189251Ssam	 *
541189251Ssam	 * Note that while MACHINE is decided at run-time,
542189251Ssam	 * MACHINE_ARCH is always known at compile time.
543189251Ssam	 */
544189251Ssam	if (!machine) {
545189251Ssam#ifndef MACHINE
546189251Ssam	    struct utsname utsname;
547189251Ssam
548189251Ssam	    if (uname(&utsname) == -1) {
549189251Ssam		    perror("make: uname");
550189251Ssam		    exit(2);
551189251Ssam	    }
552189251Ssam	    machine = utsname.machine;
553189251Ssam#else
554189251Ssam	    machine = MACHINE;
555189251Ssam#endif
556189251Ssam	}
557189251Ssam
558189251Ssam	if (!machine_arch) {
559189251Ssam#ifndef MACHINE_ARCH
560189251Ssam		machine_arch = "unknown";
561189251Ssam#else
562189251Ssam		machine_arch = MACHINE_ARCH;
563189251Ssam#endif
564189251Ssam	}
565189251Ssam
566189251Ssam	/*
567189251Ssam	 * Set machine_cpu to the minumum supported CPU revision based
568189251Ssam	 * on the target architecture, if not already set.
569189251Ssam	 */
570189251Ssam	if (!machine_cpu) {
571189251Ssam		if (!strcmp(machine_arch, "i386"))
572189251Ssam			machine_cpu = "i386";
573189251Ssam		else if (!strcmp(machine_arch, "alpha"))
574189251Ssam			machine_cpu = "ev4";
575189251Ssam		else
576189251Ssam			machine_cpu = "unknown";
577189251Ssam	}
578189251Ssam
579189251Ssam	/*
580189251Ssam	 * The object directory location is determined using the
581189251Ssam	 * following order of preference:
582189251Ssam	 *
583189251Ssam	 *	1. MAKEOBJDIRPREFIX`cwd`
584189251Ssam	 *	2. MAKEOBJDIR
585189251Ssam	 *	3. _PATH_OBJDIR.${MACHINE}
586189251Ssam	 *	4. _PATH_OBJDIR
587189251Ssam	 *	5. _PATH_OBJDIRPREFIX`cwd`
588189251Ssam	 *
589189251Ssam	 * If one of the first two fails, use the current directory.
590189251Ssam	 * If the remaining three all fail, use the current directory.
591189251Ssam	 *
592189251Ssam	 * Once things are initted,
593189251Ssam	 * have to add the original directory to the search path,
594189251Ssam	 * and modify the paths for the Makefiles apropriately.  The
595189251Ssam	 * current directory is also placed as a variable for make scripts.
596189251Ssam	 */
597189251Ssam	if (!(pathp = getenv("MAKEOBJDIRPREFIX"))) {
598189251Ssam		if (!(path = getenv("MAKEOBJDIR"))) {
599189251Ssam			path = _PATH_OBJDIR;
600189251Ssam			pathp = _PATH_OBJDIRPREFIX;
601189251Ssam			(void) snprintf(mdpath, MAXPATHLEN, "%s.%s",
602189251Ssam					path, machine);
603189251Ssam			if (!(objdir = chdir_verify_path(mdpath, obpath)))
604189251Ssam				if (!(objdir=chdir_verify_path(path, obpath))) {
605189251Ssam					(void) snprintf(mdpath, MAXPATHLEN,
606189251Ssam							"%s%s", pathp, curdir);
607189251Ssam					if (!(objdir=chdir_verify_path(mdpath,
608189251Ssam								       obpath)))
609189251Ssam						objdir = curdir;
610189251Ssam				}
611189251Ssam		}
612189251Ssam		else if (!(objdir = chdir_verify_path(path, obpath)))
613189251Ssam			objdir = curdir;
614189251Ssam	}
615189251Ssam	else {
616189251Ssam		(void) snprintf(mdpath, MAXPATHLEN, "%s%s", pathp, curdir);
617189251Ssam		if (!(objdir = chdir_verify_path(mdpath, obpath)))
618189251Ssam			objdir = curdir;
619189251Ssam	}
620189251Ssam
621189251Ssam#ifdef WANT_ENV_PWD
622189251Ssam	setenv("PWD", objdir, 1);
623189251Ssam#endif
624189251Ssam
625189251Ssam	create = Lst_Init(FALSE);
626189251Ssam	makefiles = Lst_Init(FALSE);
627189251Ssam	envFirstVars = Lst_Init(FALSE);
628189251Ssam	printVars = FALSE;
629189251Ssam	expandVars = TRUE;
630189251Ssam	variables = Lst_Init(FALSE);
631189251Ssam	beSilent = FALSE;		/* Print commands as executed */
632189251Ssam	ignoreErrors = FALSE;		/* Pay attention to non-zero returns */
633189251Ssam	noExecute = FALSE;		/* Execute all commands */
634189251Ssam	keepgoing = FALSE;		/* Stop on error */
635189251Ssam	allPrecious = FALSE;		/* Remove targets when interrupted */
636189251Ssam	queryFlag = FALSE;		/* This is not just a check-run */
637189251Ssam	noBuiltins = FALSE;		/* Read the built-in rules */
638189251Ssam	touchFlag = FALSE;		/* Actually update targets */
639189251Ssam	usePipes = TRUE;		/* Catch child output in pipes */
640189251Ssam	debug = 0;			/* No debug verbosity, please. */
641189251Ssam	jobsRunning = FALSE;
642189251Ssam
643189251Ssam	maxLocal = DEFMAXLOCAL;		/* Set default local max concurrency */
644189251Ssam#ifdef REMOTE
645189251Ssam	maxJobs = DEFMAXJOBS;		/* Set default max concurrency */
646189251Ssam#else
647189251Ssam	maxJobs = maxLocal;
648189251Ssam#endif
649189251Ssam	forceJobs = FALSE;              /* No -j flag */
650189251Ssam	compatMake = FALSE;		/* No compat mode */
651189251Ssam
652189251Ssam
653189251Ssam	/*
654189251Ssam	 * Initialize the parsing, directory and variable modules to prepare
655189251Ssam	 * for the reading of inclusion paths and variable settings on the
656189251Ssam	 * command line
657189251Ssam	 */
658189251Ssam	Dir_Init();		/* Initialize directory structures so -I flags
659189251Ssam				 * can be processed correctly */
660189251Ssam	Parse_Init();		/* Need to initialize the paths of #include
661189251Ssam				 * directories */
662189251Ssam	Var_Init();		/* As well as the lists of variables for
663189251Ssam				 * parsing arguments */
664189251Ssam        str_init();
665189251Ssam	if (objdir != curdir)
666189251Ssam		Dir_AddDir(dirSearchPath, curdir);
667189251Ssam	Var_Set(".CURDIR", curdir, VAR_GLOBAL);
668189251Ssam	Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
669189251Ssam
670189251Ssam	/*
671189251Ssam	 * Initialize various variables.
672189251Ssam	 *	MAKE also gets this name, for compatibility
673189251Ssam	 *	.MAKEFLAGS gets set to the empty string just in case.
674189251Ssam	 *	MFLAGS also gets initialized empty, for compatibility.
675189251Ssam	 */
676189251Ssam	Var_Set("MAKE", argv[0], VAR_GLOBAL);
677189251Ssam	Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
678189251Ssam	Var_Set("MFLAGS", "", VAR_GLOBAL);
679189251Ssam	Var_Set("MACHINE", machine, VAR_GLOBAL);
680189251Ssam	Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
681189251Ssam	Var_Set("MACHINE_CPU", machine_cpu, VAR_GLOBAL);
682189251Ssam
683189251Ssam	/*
684189251Ssam	 * First snag any flags out of the MAKE environment variable.
685189251Ssam	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
686189251Ssam	 * in a different format).
687189251Ssam	 */
688189251Ssam#ifdef POSIX
689189251Ssam	Main_ParseArgLine(getenv("MAKEFLAGS"));
690189251Ssam#else
691189251Ssam	Main_ParseArgLine(getenv("MAKE"));
692189251Ssam#endif
693189251Ssam
694189251Ssam	MainParseArgs(argc, argv);
695189251Ssam
696189251Ssam	/*
697189251Ssam	 * Be compatible if user did not specify -j and did not explicitly
698189251Ssam	 * turned compatibility on
699189251Ssam	 */
700189251Ssam	if (!compatMake && !forceJobs)
701189251Ssam		compatMake = TRUE;
702189251Ssam
703189251Ssam	/*
704189251Ssam	 * Initialize archive, target and suffix modules in preparation for
705209158Srpaulo	 * parsing the makefile(s)
706189251Ssam	 */
707189251Ssam	Arch_Init();
708189251Ssam	Targ_Init();
709189251Ssam	Suff_Init();
710189251Ssam
711189251Ssam	DEFAULT = NULL;
712189251Ssam	(void)time(&now);
713189251Ssam
714189251Ssam	/*
715189251Ssam	 * Set up the .TARGETS variable to contain the list of targets to be
716189251Ssam	 * created. If none specified, make the variable empty -- the parser
717189251Ssam	 * will fill the thing in with the default or .MAIN target.
718189251Ssam	 */
719189251Ssam	if (!Lst_IsEmpty(create)) {
720189251Ssam		LstNode ln;
721189251Ssam
722189251Ssam		for (ln = Lst_First(create); ln != NULL;
723189251Ssam		    ln = Lst_Succ(ln)) {
724189251Ssam			char *name = (char *)Lst_Datum(ln);
725189251Ssam
726189251Ssam			Var_Append(".TARGETS", name, VAR_GLOBAL);
727189251Ssam		}
728189251Ssam	} else
729189251Ssam		Var_Set(".TARGETS", "", VAR_GLOBAL);
730189251Ssam
731189251Ssam
732189251Ssam	/*
733189251Ssam	 * If no user-supplied system path was given (through the -m option)
734189251Ssam	 * add the directories from the DEFSYSPATH (more than one may be given
735189251Ssam	 * as dir1:...:dirn) to the system include path.
736189251Ssam	 */
737189251Ssam	if (Lst_IsEmpty(sysIncPath)) {
738189251Ssam		for (start = syspath; *start != '\0'; start = cp) {
739189251Ssam			for (cp = start; *cp != '\0' && *cp != ':'; cp++)
740189251Ssam				continue;
741189251Ssam			if (*cp == '\0') {
742189251Ssam				Dir_AddDir(sysIncPath, start);
743189251Ssam			} else {
744189251Ssam				*cp++ = '\0';
745189251Ssam				Dir_AddDir(sysIncPath, start);
746189251Ssam			}
747189251Ssam		}
748189251Ssam	}
749189251Ssam
750189251Ssam	/*
751189251Ssam	 * Read in the built-in rules first, followed by the specified
752189251Ssam	 * makefile, if it was (makefile != (char *) NULL), or the default
753189251Ssam	 * Makefile and makefile, in that order, if it wasn't.
754189251Ssam	 */
755189251Ssam	if (!noBuiltins) {
756189251Ssam		LstNode ln;
757189251Ssam
758189251Ssam		sysMkPath = Lst_Init (FALSE);
759189251Ssam		Dir_Expand (_PATH_DEFSYSMK, sysIncPath, sysMkPath);
760189251Ssam		if (Lst_IsEmpty(sysMkPath))
761189251Ssam			Fatal("make: no system rules (%s).", _PATH_DEFSYSMK);
762189251Ssam		ln = Lst_Find(sysMkPath, (void *)NULL, ReadMakefile);
763189251Ssam		if (ln != NULL)
764189251Ssam			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
765189251Ssam	}
766189251Ssam
767189251Ssam	if (!Lst_IsEmpty(makefiles)) {
768189251Ssam		LstNode ln;
769189251Ssam
770189251Ssam		ln = Lst_Find(makefiles, (void *)NULL, ReadMakefile);
771189251Ssam		if (ln != NULL)
772189251Ssam			Fatal("make: cannot open %s.", (char *)Lst_Datum(ln));
773189251Ssam	} else if (!ReadMakefile("makefile", NULL))
774189251Ssam		(void)ReadMakefile("Makefile", NULL);
775189251Ssam
776189251Ssam	(void)ReadMakefile(".depend", NULL);
777189251Ssam
778189251Ssam	Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
779189251Ssam	efree(p1);
780189251Ssam
781189251Ssam	/* Install all the flags into the MAKE envariable. */
782189251Ssam	if (((p = Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1)) != NULL) && *p)
783189251Ssam#ifdef POSIX
784189251Ssam		setenv("MAKEFLAGS", p, 1);
785189251Ssam#else
786189251Ssam		setenv("MAKE", p, 1);
787189251Ssam#endif
788189251Ssam	efree(p1);
789189251Ssam
790189251Ssam	/*
791189251Ssam	 * For compatibility, look at the directories in the VPATH variable
792189251Ssam	 * and add them to the search path, if the variable is defined. The
793189251Ssam	 * variable's value is in the same format as the PATH envariable, i.e.
794189251Ssam	 * <directory>:<directory>:<directory>...
795189251Ssam	 */
796189251Ssam	if (Var_Exists("VPATH", VAR_CMD)) {
797189251Ssam		char *vpath, *path, *cp, savec;
798189251Ssam		/*
799189251Ssam		 * GCC stores string constants in read-only memory, but
800189251Ssam		 * Var_Subst will want to write this thing, so store it
801189251Ssam		 * in an array
802189251Ssam		 */
803189251Ssam		static char VPATH[] = "${VPATH}";
804189251Ssam
805189251Ssam		vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
806189251Ssam		path = vpath;
807189251Ssam		do {
808189251Ssam			/* skip to end of directory */
809189251Ssam			for (cp = path; *cp != ':' && *cp != '\0'; cp++)
810189251Ssam				continue;
811189251Ssam			/* Save terminator character so know when to stop */
812189251Ssam			savec = *cp;
813189251Ssam			*cp = '\0';
814189251Ssam			/* Add directory to search path */
815189251Ssam			Dir_AddDir(dirSearchPath, path);
816189251Ssam			*cp = savec;
817189251Ssam			path = cp + 1;
818189251Ssam		} while (savec == ':');
819189251Ssam		(void)free(vpath);
820189251Ssam	}
821189251Ssam
822189251Ssam	/*
823189251Ssam	 * Now that all search paths have been read for suffixes et al, it's
824189251Ssam	 * time to add the default search path to their lists...
825189251Ssam	 */
826189251Ssam	Suff_DoPaths();
827189251Ssam
828189251Ssam	/* print the initial graph, if the user requested it */
829189251Ssam	if (DEBUG(GRAPH1))
830189251Ssam		Targ_PrintGraph(1);
831189251Ssam
832189251Ssam	/* print the values of any variables requested by the user */
833189251Ssam	if (printVars) {
834189251Ssam		LstNode ln;
835189251Ssam
836189251Ssam		for (ln = Lst_First(variables); ln != NULL;
837189251Ssam		    ln = Lst_Succ(ln)) {
838189251Ssam			char *value;
839189251Ssam			if (expandVars) {
840189251Ssam				p1 = malloc(strlen((char *)Lst_Datum(ln)) + 1 + 3);
841189251Ssam				if (!p1)
842189251Ssam					Punt("make: cannot allocate memory.");
843189251Ssam				/* This sprintf is safe, because of the malloc above */
844189251Ssam				(void)sprintf(p1, "${%s}", (char *)Lst_Datum(ln));
845189251Ssam				value = Var_Subst(NULL, p1, VAR_GLOBAL, FALSE);
846189251Ssam			} else {
847189251Ssam				value = Var_Value((char *)Lst_Datum(ln),
848189251Ssam						  VAR_GLOBAL, &p1);
849189251Ssam			}
850189251Ssam			printf("%s\n", value ? value : "");
851189251Ssam			if (p1)
852189251Ssam				free(p1);
853189251Ssam		}
854189251Ssam	}
855189251Ssam
856189251Ssam	/*
857189251Ssam	 * Have now read the entire graph and need to make a list of targets
858189251Ssam	 * to create. If none was given on the command line, we consult the
859189251Ssam	 * parsing module to find the main target(s) to create.
860189251Ssam	 */
861189251Ssam	if (Lst_IsEmpty(create))
862189251Ssam		targs = Parse_MainName();
863189251Ssam	else
864189251Ssam		targs = Targ_FindList(create, TARG_CREATE);
865189251Ssam
866189251Ssam	if (!compatMake && !printVars) {
867189251Ssam		/*
868189251Ssam		 * Initialize job module before traversing the graph, now that
869189251Ssam		 * any .BEGIN and .END targets have been read.  This is done
870189251Ssam		 * only if the -q flag wasn't given (to prevent the .BEGIN from
871189251Ssam		 * being executed should it exist).
872189251Ssam		 */
873189251Ssam		if (!queryFlag) {
874189251Ssam			if (maxLocal == -1)
875189251Ssam				maxLocal = maxJobs;
876189251Ssam			Job_Init(maxJobs, maxLocal);
877189251Ssam			jobsRunning = TRUE;
878189251Ssam		}
879189251Ssam
880189251Ssam		/* Traverse the graph, checking on all the targets */
881189251Ssam		outOfDate = Make_Run(targs);
882189251Ssam	} else if (!printVars) {
883189251Ssam		/*
884189251Ssam		 * Compat_Init will take care of creating all the targets as
885189251Ssam		 * well as initializing the module.
886189251Ssam		 */
887189251Ssam		Compat_Run(targs);
888189251Ssam	}
889189251Ssam
890189251Ssam	Lst_Destroy(targs, NOFREE);
891189251Ssam	Lst_Destroy(variables, NOFREE);
892189251Ssam	Lst_Destroy(makefiles, NOFREE);
893189251Ssam	Lst_Destroy(create, (void (*) __P((void *))) free);
894189251Ssam
895189251Ssam	/* print the graph now it's been processed if the user requested it */
896189251Ssam	if (DEBUG(GRAPH2))
897189251Ssam		Targ_PrintGraph(2);
898189251Ssam
899189251Ssam	Suff_End();
900189251Ssam        Targ_End();
901189251Ssam	Arch_End();
902189251Ssam	str_end();
903189251Ssam	Var_End();
904189251Ssam	Parse_End();
905189251Ssam	Dir_End();
906189251Ssam
907189251Ssam	if (queryFlag && outOfDate)
908189251Ssam		return(1);
909189251Ssam	else
910189251Ssam		return(0);
911189251Ssam}
912189251Ssam
913189251Ssam/*-
914189251Ssam * ReadMakefile  --
915189251Ssam *	Open and parse the given makefile.
916189251Ssam *
917189251Ssam * Results:
918189251Ssam *	TRUE if ok. FALSE if couldn't open file.
919189251Ssam *
920189251Ssam * Side Effects:
921189251Ssam *	lots
922189251Ssam */
923189251Ssamstatic Boolean
924189251SsamReadMakefile(p, q)
925189251Ssam	void *p;
926189251Ssam	void *q;
927189251Ssam{
928189251Ssam	char *fname = p;		/* makefile to read */
929189251Ssam	extern Lst parseIncPath;
930189251Ssam	FILE *stream;
931189251Ssam	char *name, path[MAXPATHLEN];
932189251Ssam
933189251Ssam	if (!strcmp(fname, "-")) {
934189251Ssam		Parse_File("(stdin)", stdin);
935189251Ssam		Var_Set("MAKEFILE", "", VAR_GLOBAL);
936189251Ssam	} else {
937189251Ssam		/* if we've chdir'd, rebuild the path name */
938189251Ssam		if (curdir != objdir && *fname != '/') {
939189251Ssam			(void)snprintf(path, MAXPATHLEN, "%s/%s", curdir, fname);
940189251Ssam			if ((stream = fopen(path, "r")) != NULL) {
941189251Ssam				fname = path;
942189251Ssam				goto found;
943189251Ssam			}
944189251Ssam		} else if ((stream = fopen(fname, "r")) != NULL)
945189251Ssam			goto found;
946189251Ssam		/* look in -I and system include directories. */
947189251Ssam		name = Dir_FindFile(fname, parseIncPath);
948189251Ssam		if (!name)
949189251Ssam			name = Dir_FindFile(fname, sysIncPath);
950189251Ssam		if (!name || !(stream = fopen(name, "r")))
951189251Ssam			return(FALSE);
952189251Ssam		fname = name;
953189251Ssam		/*
954189251Ssam		 * set the MAKEFILE variable desired by System V fans -- the
955189251Ssam		 * placement of the setting here means it gets set to the last
956189251Ssam		 * makefile specified, as it is set by SysV make.
957189251Ssam		 */
958189251Ssamfound:		Var_Set("MAKEFILE", fname, VAR_GLOBAL);
959189251Ssam		Parse_File(fname, stream);
960189251Ssam		(void)fclose(stream);
961189251Ssam	}
962189251Ssam	return(TRUE);
963189251Ssam}
964189251Ssam
965189251Ssam/*-
966189251Ssam * Cmd_Exec --
967189251Ssam *	Execute the command in cmd, and return the output of that command
968189251Ssam *	in a string.
969189251Ssam *
970189251Ssam * Results:
971189251Ssam *	A string containing the output of the command, or the empty string
972189251Ssam *	If err is not NULL, it contains the reason for the command failure
973189251Ssam *
974189251Ssam * Side Effects:
975189251Ssam *	The string must be freed by the caller.
976189251Ssam */
977189251Ssamchar *
978189251SsamCmd_Exec(cmd, err)
979189251Ssam    char *cmd;
980189251Ssam    char **err;
981189251Ssam{
982189251Ssam    char	*args[4];   	/* Args for invoking the shell */
983189251Ssam    int 	fds[2];	    	/* Pipe streams */
984189251Ssam    int 	cpid;	    	/* Child PID */
985189251Ssam    int 	pid;	    	/* PID from wait() */
986189251Ssam    char	*res;		/* result */
987189251Ssam    int		status;		/* command exit status */
988189251Ssam    Buffer	buf;		/* buffer to store the result */
989189251Ssam    char	*cp;
990189251Ssam    int		cc;
991189251Ssam
992189251Ssam
993189251Ssam    *err = NULL;
994189251Ssam
995189251Ssam    /*
996189251Ssam     * Set up arguments for shell
997189251Ssam     */
998189251Ssam    args[0] = "sh";
999189251Ssam    args[1] = "-c";
1000189251Ssam    args[2] = cmd;
1001189251Ssam    args[3] = NULL;
1002189251Ssam
1003189251Ssam    /*
1004189251Ssam     * Open a pipe for fetching its output
1005189251Ssam     */
1006189251Ssam    if (pipe(fds) == -1) {
1007189251Ssam	*err = "Couldn't create pipe for \"%s\"";
1008189251Ssam	goto bad;
1009189251Ssam    }
1010189251Ssam
1011189251Ssam    /*
1012189251Ssam     * Fork
1013189251Ssam     */
1014189251Ssam    switch (cpid = vfork()) {
1015189251Ssam    case 0:
1016189251Ssam	/*
1017189251Ssam	 * Close input side of pipe
1018189251Ssam	 */
1019189251Ssam	(void) close(fds[0]);
1020189251Ssam
1021189251Ssam	/*
1022189251Ssam	 * Duplicate the output stream to the shell's output, then
1023189251Ssam	 * shut the extra thing down. Note we don't fetch the error
1024189251Ssam	 * stream...why not? Why?
1025189251Ssam	 */
1026189251Ssam	(void) dup2(fds[1], 1);
1027189251Ssam	(void) close(fds[1]);
1028189251Ssam
1029189251Ssam#if DEFSHELL == 1
1030189251Ssam	(void) execv("/bin/sh", args);
1031189251Ssam#elif DEFSHELL == 2
1032189251Ssam	(void) execv("/bin/ksh", args);
1033189251Ssam#else
1034189251Ssam#error "DEFSHELL must be 1 or 2."
1035189251Ssam#endif
1036189251Ssam	_exit(1);
1037189251Ssam	/*NOTREACHED*/
1038189251Ssam
1039189251Ssam    case -1:
1040189251Ssam	*err = "Couldn't exec \"%s\"";
1041189251Ssam	goto bad;
1042189251Ssam
1043189251Ssam    default:
1044189251Ssam	/*
1045189251Ssam	 * No need for the writing half
1046189251Ssam	 */
1047189251Ssam	(void) close(fds[1]);
1048189251Ssam
1049189251Ssam	buf = Buf_Init (MAKE_BSIZE);
1050189251Ssam
1051189251Ssam	do {
1052189251Ssam	    char   result[BUFSIZ];
1053189251Ssam	    cc = read(fds[0], result, sizeof(result));
1054189251Ssam	    if (cc > 0)
1055189251Ssam		Buf_AddBytes(buf, cc, (Byte *) result);
1056189251Ssam	}
1057189251Ssam	while (cc > 0 || (cc == -1 && errno == EINTR));
1058189251Ssam
1059189251Ssam	/*
1060189251Ssam	 * Close the input side of the pipe.
1061189251Ssam	 */
1062189251Ssam	(void) close(fds[0]);
1063189251Ssam
1064189251Ssam	/*
1065189251Ssam	 * Wait for the process to exit.
1066189251Ssam	 */
1067189251Ssam	while(((pid = wait(&status)) != cpid) && (pid >= 0))
1068189251Ssam	    continue;
1069189251Ssam
1070189251Ssam	if (cc == -1)
1071189251Ssam	    *err = "Error reading shell's output for \"%s\"";
1072189251Ssam
1073189251Ssam	res = (char *)Buf_GetAll (buf, &cc);
1074189251Ssam	Buf_Destroy (buf, FALSE);
1075189251Ssam
1076189251Ssam	if (status)
1077189251Ssam	    *err = "\"%s\" returned non-zero status";
1078189251Ssam
1079189251Ssam	/*
1080189251Ssam	 * Null-terminate the result, convert newlines to spaces and
1081189251Ssam	 * install it in the variable.
1082189251Ssam	 */
1083189251Ssam	res[cc] = '\0';
1084189251Ssam	cp = &res[cc] - 1;
1085189251Ssam
1086189251Ssam	if (*cp == '\n') {
1087189251Ssam	    /*
1088189251Ssam	     * A final newline is just stripped
1089189251Ssam	     */
1090189251Ssam	    *cp-- = '\0';
1091189251Ssam	}
1092189251Ssam	while (cp >= res) {
1093189251Ssam	    if (*cp == '\n') {
1094189251Ssam		*cp = ' ';
1095189251Ssam	    }
1096189251Ssam	    cp--;
1097189251Ssam	}
1098189251Ssam	break;
1099189251Ssam    }
1100189251Ssam    return res;
1101189251Ssambad:
1102189251Ssam    res = emalloc(1);
1103189251Ssam    *res = '\0';
1104189251Ssam    return res;
1105189251Ssam}
1106189251Ssam
1107189251Ssam/*-
1108189251Ssam * Error --
1109189251Ssam *	Print an error message given its format.
1110189251Ssam *
1111189251Ssam * Results:
1112189251Ssam *	None.
1113189251Ssam *
1114189251Ssam * Side Effects:
1115189251Ssam *	The message is printed.
1116189251Ssam */
1117189251Ssam/* VARARGS */
1118189251Ssamvoid
1119189251Ssam#ifdef __STDC__
1120189251SsamError(char *fmt, ...)
1121189251Ssam#else
1122189251SsamError(va_alist)
1123189251Ssam	va_dcl
1124189251Ssam#endif
1125189251Ssam{
1126189251Ssam	va_list ap;
1127189251Ssam#ifdef __STDC__
1128189251Ssam	va_start(ap, fmt);
1129189251Ssam#else
1130189251Ssam	char *fmt;
1131189251Ssam
1132189251Ssam	va_start(ap);
1133189251Ssam	fmt = va_arg(ap, char *);
1134189251Ssam#endif
1135189251Ssam	(void)vfprintf(stderr, fmt, ap);
1136189251Ssam	va_end(ap);
1137189251Ssam	(void)fprintf(stderr, "\n");
1138189251Ssam	(void)fflush(stderr);
1139189251Ssam}
1140189251Ssam
1141189251Ssam/*-
1142189251Ssam * Fatal --
1143189251Ssam *	Produce a Fatal error message. If jobs are running, waits for them
1144189251Ssam *	to finish.
1145189251Ssam *
1146189251Ssam * Results:
1147189251Ssam *	None
1148189251Ssam *
1149189251Ssam * Side Effects:
1150189251Ssam *	The program exits
1151189251Ssam */
1152189251Ssam/* VARARGS */
1153189251Ssamvoid
1154189251Ssam#ifdef __STDC__
1155189251SsamFatal(char *fmt, ...)
1156189251Ssam#else
1157189251SsamFatal(va_alist)
1158189251Ssam	va_dcl
1159189251Ssam#endif
1160189251Ssam{
1161189251Ssam	va_list ap;
1162189251Ssam#ifdef __STDC__
1163189251Ssam	va_start(ap, fmt);
1164189251Ssam#else
1165189251Ssam	char *fmt;
1166189251Ssam
1167189251Ssam	va_start(ap);
1168189251Ssam	fmt = va_arg(ap, char *);
1169189251Ssam#endif
1170189251Ssam	if (jobsRunning)
1171189251Ssam		Job_Wait();
1172189251Ssam
1173189251Ssam	(void)vfprintf(stderr, fmt, ap);
1174189251Ssam	va_end(ap);
1175189251Ssam	(void)fprintf(stderr, "\n");
1176189251Ssam	(void)fflush(stderr);
1177189251Ssam
1178189251Ssam	if (DEBUG(GRAPH2))
1179189251Ssam		Targ_PrintGraph(2);
1180189251Ssam	exit(2);		/* Not 1 so -q can distinguish error */
1181189251Ssam}
1182189251Ssam
1183189251Ssam/*
1184189251Ssam * Punt --
1185189251Ssam *	Major exception once jobs are being created. Kills all jobs, prints
1186189251Ssam *	a message and exits.
1187189251Ssam *
1188189251Ssam * Results:
1189189251Ssam *	None
1190189251Ssam *
1191189251Ssam * Side Effects:
1192189251Ssam *	All children are killed indiscriminately and the program Lib_Exits
1193189251Ssam */
1194189251Ssam/* VARARGS */
1195189251Ssamvoid
1196189251Ssam#ifdef __STDC__
1197189251SsamPunt(char *fmt, ...)
1198189251Ssam#else
1199189251SsamPunt(va_alist)
1200189251Ssam	va_dcl
1201189251Ssam#endif
1202189251Ssam{
1203189251Ssam	va_list ap;
1204189251Ssam#if __STDC__
1205189251Ssam	va_start(ap, fmt);
1206189251Ssam#else
1207189251Ssam	char *fmt;
1208189251Ssam
1209189251Ssam	va_start(ap);
1210189251Ssam	fmt = va_arg(ap, char *);
1211189251Ssam#endif
1212189251Ssam
1213189251Ssam	(void)fprintf(stderr, "make: ");
1214189251Ssam	(void)vfprintf(stderr, fmt, ap);
1215189251Ssam	va_end(ap);
1216189251Ssam	(void)fprintf(stderr, "\n");
1217189251Ssam	(void)fflush(stderr);
1218189251Ssam
1219189251Ssam	DieHorribly();
1220189251Ssam}
1221189251Ssam
1222189251Ssam/*-
1223189251Ssam * DieHorribly --
1224189251Ssam *	Exit without giving a message.
1225189251Ssam *
1226189251Ssam * Results:
1227189251Ssam *	None
1228189251Ssam *
1229189251Ssam * Side Effects:
1230189251Ssam *	A big one...
1231189251Ssam */
1232189251Ssamvoid
1233189251SsamDieHorribly()
1234189251Ssam{
1235189251Ssam	if (jobsRunning)
1236189251Ssam		Job_AbortAll();
1237189251Ssam	if (DEBUG(GRAPH2))
1238189251Ssam		Targ_PrintGraph(2);
1239189251Ssam	exit(2);		/* Not 1, so -q can distinguish error */
1240189251Ssam}
1241189251Ssam
1242189251Ssam/*
1243189251Ssam * Finish --
1244189251Ssam *	Called when aborting due to errors in child shell to signal
1245189251Ssam *	abnormal exit.
1246189251Ssam *
1247189251Ssam * Results:
1248189251Ssam *	None
1249189251Ssam *
1250189251Ssam * Side Effects:
1251189251Ssam *	The program exits
1252189251Ssam */
1253189251Ssamvoid
1254189251SsamFinish(errors)
1255189251Ssam	int errors;	/* number of errors encountered in Make_Make */
1256189251Ssam{
1257189251Ssam	Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1258189251Ssam}
1259189251Ssam
1260189251Ssam/*
1261189251Ssam * emalloc --
1262189251Ssam *	malloc, but die on error.
1263189251Ssam */
1264189251Ssamvoid *
1265189251Ssamemalloc(len)
1266189251Ssam	size_t len;
1267189251Ssam{
1268189251Ssam	void *p;
1269189251Ssam
1270189251Ssam	if ((p = malloc(len)) == NULL)
1271189251Ssam		enomem();
1272189251Ssam	return(p);
1273189251Ssam}
1274189251Ssam
1275189251Ssam/*
1276189251Ssam * estrdup --
1277189251Ssam *	strdup, but die on error.
1278189251Ssam */
1279189251Ssamchar *
1280189251Ssamestrdup(str)
1281189251Ssam	const char *str;
1282189251Ssam{
1283189251Ssam	char *p;
1284189251Ssam
1285189251Ssam	if ((p = strdup(str)) == NULL)
1286189251Ssam		enomem();
1287189251Ssam	return(p);
1288189251Ssam}
1289189251Ssam
1290189251Ssam/*
1291189251Ssam * erealloc --
1292189251Ssam *	realloc, but die on error.
1293189251Ssam */
1294189251Ssamvoid *
1295189251Ssamerealloc(ptr, size)
1296189251Ssam	void *ptr;
1297189251Ssam	size_t size;
1298189251Ssam{
1299189251Ssam	if ((ptr = realloc(ptr, size)) == NULL)
1300189251Ssam		enomem();
1301189251Ssam	return(ptr);
1302189251Ssam}
1303189251Ssam
1304189251Ssam/*
1305189251Ssam * enomem --
1306189251Ssam *	die when out of memory.
1307189251Ssam */
1308189251Ssamvoid
1309189251Ssamenomem()
1310189251Ssam{
1311189251Ssam	err(2, NULL);
1312189251Ssam}
1313189251Ssam
1314189251Ssam/*
1315189251Ssam * enunlink --
1316189251Ssam *	Remove a file carefully, avoiding directories.
1317189251Ssam */
1318189251Ssamint
1319189251Ssameunlink(file)
1320189251Ssam	const char *file;
1321189251Ssam{
1322189251Ssam	struct stat st;
1323189251Ssam
1324189251Ssam	if (lstat(file, &st) == -1)
1325189251Ssam		return -1;
1326
1327	if (S_ISDIR(st.st_mode)) {
1328		errno = EISDIR;
1329		return -1;
1330	}
1331	return unlink(file);
1332}
1333
1334/*
1335 * usage --
1336 *	exit with usage message
1337 */
1338static void
1339usage()
1340{
1341	(void)fprintf(stderr, "%s\n%s\n%s\n",
1342"usage: make [-Beiknqrstv] [-D variable] [-d flags] [-E variable] [-f makefile]",
1343"            [-I directory] [-j max_jobs] [-m directory] [-V variable]",
1344"            [variable=value] [target ...]");
1345	exit(2);
1346}
1347
1348
1349int
1350PrintAddr(a, b)
1351    void * a;
1352    void * b;
1353{
1354    printf("%lx ", (unsigned long) a);
1355    return b ? 0 : 0;
1356}
1357