xref: /netbsd-src/usr.bin/make/main.c (revision ce2c90c7c172d95d2402a5b3d96d8f8e6d138a21)
1 /*	$NetBSD: main.c,v 1.133 2006/10/15 08:38:21 dsl Exp $	*/
2 
3 /*
4  * Copyright (c) 1988, 1989, 1990, 1993
5  *	The Regents of the University of California.  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. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 /*
36  * Copyright (c) 1989 by Berkeley Softworks
37  * All rights reserved.
38  *
39  * This code is derived from software contributed to Berkeley by
40  * Adam de Boor.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  * 3. All advertising materials mentioning features or use of this software
51  *    must display the following acknowledgement:
52  *	This product includes software developed by the University of
53  *	California, Berkeley and its contributors.
54  * 4. Neither the name of the University nor the names of its contributors
55  *    may be used to endorse or promote products derived from this software
56  *    without specific prior written permission.
57  *
58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68  * SUCH DAMAGE.
69  */
70 
71 #ifndef MAKE_NATIVE
72 static char rcsid[] = "$NetBSD: main.c,v 1.133 2006/10/15 08:38:21 dsl Exp $";
73 #else
74 #include <sys/cdefs.h>
75 #ifndef lint
76 __COPYRIGHT("@(#) Copyright (c) 1988, 1989, 1990, 1993\n\
77 	The Regents of the University of California.  All rights reserved.\n");
78 #endif /* not lint */
79 
80 #ifndef lint
81 #if 0
82 static char sccsid[] = "@(#)main.c	8.3 (Berkeley) 3/19/94";
83 #else
84 __RCSID("$NetBSD: main.c,v 1.133 2006/10/15 08:38:21 dsl Exp $");
85 #endif
86 #endif /* not lint */
87 #endif
88 
89 /*-
90  * main.c --
91  *	The main file for this entire program. Exit routines etc
92  *	reside here.
93  *
94  * Utility functions defined in this file:
95  *	Main_ParseArgLine	Takes a line of arguments, breaks them and
96  *				treats them as if they were given when first
97  *				invoked. Used by the parse module to implement
98  *				the .MFLAGS target.
99  *
100  *	Error			Print a tagged error message. The global
101  *				MAKE variable must have been defined. This
102  *				takes a format string and two optional
103  *				arguments for it.
104  *
105  *	Fatal			Print an error message and exit. Also takes
106  *				a format string and two arguments.
107  *
108  *	Punt			Aborts all jobs and exits with a message. Also
109  *				takes a format string and two arguments.
110  *
111  *	Finish			Finish things up by printing the number of
112  *				errors which occurred, as passed to it, and
113  *				exiting.
114  */
115 
116 #include <sys/types.h>
117 #include <sys/time.h>
118 #include <sys/param.h>
119 #include <sys/resource.h>
120 #include <sys/signal.h>
121 #include <sys/stat.h>
122 #ifdef MAKE_NATIVE
123 #include <sys/utsname.h>
124 #endif
125 #include <sys/wait.h>
126 
127 #include <errno.h>
128 #include <fcntl.h>
129 #include <stdarg.h>
130 #include <stdio.h>
131 #include <stdlib.h>
132 #include <time.h>
133 
134 #include "make.h"
135 #include "hash.h"
136 #include "dir.h"
137 #include "job.h"
138 #include "pathnames.h"
139 #include "trace.h"
140 
141 #ifdef USE_IOVEC
142 #include <sys/uio.h>
143 #endif
144 
145 #ifndef	DEFMAXLOCAL
146 #define	DEFMAXLOCAL DEFMAXJOBS
147 #endif	/* DEFMAXLOCAL */
148 
149 Lst			create;		/* Targets to be made */
150 time_t			now;		/* Time at start of make */
151 GNode			*DEFAULT;	/* .DEFAULT node */
152 Boolean			allPrecious;	/* .PRECIOUS given on line by itself */
153 
154 static Boolean		noBuiltins;	/* -r flag */
155 static Lst		makefiles;	/* ordered list of makefiles to read */
156 static Boolean		printVars;	/* print value of one or more vars */
157 static Lst		variables;	/* list of variables to print */
158 int			maxJobs;	/* -j argument */
159 static int		maxJobTokens;	/* -j argument */
160 Boolean			compatMake;	/* -B argument */
161 int			debug;		/* -d argument */
162 Boolean			noExecute;	/* -n flag */
163 Boolean			noRecursiveExecute;	/* -N flag */
164 Boolean			keepgoing;	/* -k flag */
165 Boolean			queryFlag;	/* -q flag */
166 Boolean			touchFlag;	/* -t flag */
167 Boolean			ignoreErrors;	/* -i flag */
168 Boolean			beSilent;	/* -s flag */
169 Boolean			oldVars;	/* variable substitution style */
170 Boolean			checkEnvFirst;	/* -e flag */
171 Boolean			parseWarnFatal;	/* -W flag */
172 Boolean			jobServer; 	/* -J flag */
173 static int jp_0 = -1, jp_1 = -1;	/* ends of parent job pipe */
174 Boolean			varNoExportEnv;	/* -X flag */
175 static Boolean		jobsRunning;	/* TRUE if the jobs might be running */
176 static const char *	tracefile;
177 static char *		Check_Cwd_av(int, char **, int);
178 static void		MainParseArgs(int, char **);
179 static int		ReadMakefile(ClientData, ClientData);
180 static void		usage(void);
181 
182 static char curdir[MAXPATHLEN + 1];	/* startup directory */
183 static char objdir[MAXPATHLEN + 1];	/* where we chdir'ed to */
184 char *progname;				/* the program name */
185 
186 Boolean forceJobs = FALSE;
187 
188 extern Lst parseIncPath;
189 
190 static void
191 parse_debug_options(const char *argvalue)
192 {
193 	const char *modules;
194 
195 	for (modules = argvalue; *modules; ++modules) {
196 		switch (*modules) {
197 		case 'A':
198 			debug = ~0;
199 			break;
200 		case 'a':
201 			debug |= DEBUG_ARCH;
202 			break;
203 		case 'c':
204 			debug |= DEBUG_COND;
205 			break;
206 		case 'd':
207 			debug |= DEBUG_DIR;
208 			break;
209 		case 'e':
210 			debug |= DEBUG_ERROR;
211 			break;
212 		case 'f':
213 			debug |= DEBUG_FOR;
214 			break;
215 		case 'g':
216 			if (modules[1] == '1') {
217 				debug |= DEBUG_GRAPH1;
218 				++modules;
219 			}
220 			else if (modules[1] == '2') {
221 				debug |= DEBUG_GRAPH2;
222 				++modules;
223 			}
224 			else if (modules[1] == '3') {
225 				debug |= DEBUG_GRAPH3;
226 				++modules;
227 			}
228 			break;
229 		case 'j':
230 			debug |= DEBUG_JOB;
231 			break;
232 		case 'm':
233 			debug |= DEBUG_MAKE;
234 			break;
235 		case 'n':
236 			debug |= DEBUG_SCRIPT;
237 			break;
238 		case 'p':
239 			debug |= DEBUG_PARSE;
240 			break;
241 		case 's':
242 			debug |= DEBUG_SUFF;
243 			break;
244 		case 't':
245 			debug |= DEBUG_TARG;
246 			break;
247 		case 'v':
248 			debug |= DEBUG_VAR;
249 			break;
250 		case 'x':
251 			debug |= DEBUG_SHELL;
252 			break;
253 		case 'F':
254 			if (debug_file != stdout && debug_file != stderr)
255 				fclose(debug_file);
256 			if (*++modules == '+')
257 				debug_file = fopen(++modules, "a");
258 			else {
259 				if (!strcmp(modules, "stdout"))
260 					debug_file = stdout;
261 				else if (!strcmp(modules, "stderr"))
262 					debug_file = stderr;
263 				else
264 					debug_file = fopen(modules, "w");
265 			}
266 			if (!debug_file) {
267 				fprintf(stderr, "Cannot open debug file %s",
268 				    modules);
269 				usage();
270 			}
271 			/* Have this non-buffered */
272 			if (debug_file != stdout && debug_file != stderr)
273 				setbuf(debug_file, NULL);
274 			return;
275 		default:
276 			(void)fprintf(stderr,
277 			    "%s: illegal argument to d option -- %c\n",
278 			    progname, *modules);
279 			usage();
280 		}
281 	}
282 }
283 
284 /*-
285  * MainParseArgs --
286  *	Parse a given argument vector. Called from main() and from
287  *	Main_ParseArgLine() when the .MAKEFLAGS target is used.
288  *
289  *	XXX: Deal with command line overriding .MAKEFLAGS in makefile
290  *
291  * Results:
292  *	None
293  *
294  * Side Effects:
295  *	Various global and local flags will be set depending on the flags
296  *	given
297  */
298 static void
299 MainParseArgs(int argc, char **argv)
300 {
301 	char *p;
302 	int c = '?';
303 	int arginc;
304 	char *argvalue;
305 	const char *getopt_def;
306 	char *optscan;
307 	Boolean inOption, dashDash = FALSE;
308 	char found_path[MAXPATHLEN + 1];	/* for searching for sys.mk */
309 
310 #define OPTFLAGS "BD:I:J:NST:V:WXd:ef:ij:km:nqrst"
311 /* Can't actually use getopt(3) because rescanning is not portable */
312 
313 	getopt_def = OPTFLAGS;
314 rearg:
315 	inOption = FALSE;
316 	optscan = NULL;
317 	while(argc > 1) {
318 		char *getopt_spec;
319 		if(!inOption)
320 			optscan = argv[1];
321 		c = *optscan++;
322 		arginc = 0;
323 		if(inOption) {
324 			if(c == '\0') {
325 				++argv;
326 				--argc;
327 				inOption = FALSE;
328 				continue;
329 			}
330 		} else {
331 			if (c != '-' || dashDash)
332 				break;
333 			inOption = TRUE;
334 			c = *optscan++;
335 		}
336 		/* '-' found at some earlier point */
337 		getopt_spec = strchr(getopt_def, c);
338 		if(c != '\0' && getopt_spec != NULL && getopt_spec[1] == ':') {
339 			/* -<something> found, and <something> should have an arg */
340 			inOption = FALSE;
341 			arginc = 1;
342 			argvalue = optscan;
343 			if(*argvalue == '\0') {
344 				if (argc < 3)
345 					goto noarg;
346 				argvalue = argv[2];
347 				arginc = 2;
348 			}
349 		} else {
350 			argvalue = NULL;
351 		}
352 		switch(c) {
353 		case '\0':
354 			arginc = 1;
355 			inOption = FALSE;
356 			break;
357 		case 'B':
358 			compatMake = TRUE;
359 			Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
360 			break;
361 		case 'D':
362 			if (argvalue == NULL) goto noarg;
363 			Var_Set(argvalue, "1", VAR_GLOBAL, 0);
364 			Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
365 			Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
366 			break;
367 		case 'I':
368 			if (argvalue == NULL) goto noarg;
369 			Parse_AddIncludeDir(argvalue);
370 			Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
371 			Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
372 			break;
373 		case 'J':
374 			if (argvalue == NULL) goto noarg;
375 			if (sscanf(argvalue, "%d,%d", &jp_0, &jp_1) != 2) {
376 			    (void)fprintf(stderr,
377 				"%s: internal error -- J option malformed (%s)\n",
378 				progname, argvalue);
379 				usage();
380 			}
381 			if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
382 			    (fcntl(jp_1, F_GETFD, 0) < 0)) {
383 #if 0
384 			    (void)fprintf(stderr,
385 				"%s: ###### warning -- J descriptors were closed!\n",
386 				progname);
387 			    exit(2);
388 #endif
389 			    jp_0 = -1;
390 			    jp_1 = -1;
391 			    compatMake = TRUE;
392 			} else {
393 			    Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
394 			    Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
395 			    jobServer = TRUE;
396 			}
397 			break;
398 		case 'N':
399 			noExecute = TRUE;
400 			noRecursiveExecute = TRUE;
401 			Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
402 			break;
403 		case 'S':
404 			keepgoing = FALSE;
405 			Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
406 			break;
407 		case 'T':
408 			if (argvalue == NULL) goto noarg;
409 			tracefile = estrdup(argvalue);
410 			Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
411 			Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
412 			break;
413 		case 'V':
414 			if (argvalue == NULL) goto noarg;
415 			printVars = TRUE;
416 			(void)Lst_AtEnd(variables, (ClientData)argvalue);
417 			Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
418 			Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
419 			break;
420 		case 'W':
421 			parseWarnFatal = TRUE;
422 			break;
423 		case 'X':
424 			varNoExportEnv = TRUE;
425 			Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
426 			break;
427 		case 'd':
428 			if (argvalue == NULL) goto noarg;
429 			/* If '-d-opts' don't pass to children */
430 			if (argvalue[0] == '-')
431 			    argvalue++;
432 			else {
433 			    Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
434 			    Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
435 			}
436 			parse_debug_options(argvalue);
437 			break;
438 		case 'e':
439 			checkEnvFirst = TRUE;
440 			Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
441 			break;
442 		case 'f':
443 			if (argvalue == NULL) goto noarg;
444 			(void)Lst_AtEnd(makefiles, (ClientData)argvalue);
445 			break;
446 		case 'i':
447 			ignoreErrors = TRUE;
448 			Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
449 			break;
450 		case 'j':
451 			if (argvalue == NULL) goto noarg;
452 			forceJobs = TRUE;
453 			maxJobs = strtol(argvalue, &p, 0);
454 			if (*p != '\0' || maxJobs < 1) {
455 				(void)fprintf(stderr, "%s: illegal argument to -j -- must be positive integer!\n",
456 				    progname);
457 				exit(1);
458 			}
459 			Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
460 			Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
461 			maxJobTokens = maxJobs;
462 			break;
463 		case 'k':
464 			keepgoing = TRUE;
465 			Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
466 			break;
467 		case 'm':
468 			if (argvalue == NULL) goto noarg;
469 			/* look for magic parent directory search string */
470 			if (strncmp(".../", argvalue, 4) == 0) {
471 				if (!Dir_FindHereOrAbove(curdir, argvalue+4,
472 				    found_path, sizeof(found_path)))
473 					break;		/* nothing doing */
474 				(void)Dir_AddDir(sysIncPath, found_path);
475 
476 			} else {
477 				(void)Dir_AddDir(sysIncPath, argvalue);
478 			}
479 			Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
480 			Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
481 			break;
482 		case 'n':
483 			noExecute = TRUE;
484 			Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
485 			break;
486 		case 'q':
487 			queryFlag = TRUE;
488 			/* Kind of nonsensical, wot? */
489 			Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
490 			break;
491 		case 'r':
492 			noBuiltins = TRUE;
493 			Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
494 			break;
495 		case 's':
496 			beSilent = TRUE;
497 			Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
498 			break;
499 		case 't':
500 			touchFlag = TRUE;
501 			Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
502 			break;
503 		case '-':
504 			dashDash = TRUE;
505 			break;
506 		default:
507 		case '?':
508 			usage();
509 		}
510 		argv += arginc;
511 		argc -= arginc;
512 	}
513 
514 	oldVars = TRUE;
515 
516 	/*
517 	 * See if the rest of the arguments are variable assignments and
518 	 * perform them if so. Else take them to be targets and stuff them
519 	 * on the end of the "create" list.
520 	 */
521 	for (; argc > 1; ++argv, --argc)
522 		if (Parse_IsVar(argv[1])) {
523 			Parse_DoVar(argv[1], VAR_CMD);
524 		} else {
525 			if (!*argv[1])
526 				Punt("illegal (null) argument.");
527 			if (*argv[1] == '-' && !dashDash)
528 				goto rearg;
529 			(void)Lst_AtEnd(create, (ClientData)estrdup(argv[1]));
530 		}
531 
532 	return;
533 noarg:
534 	(void)fprintf(stderr, "%s: option requires an argument -- %c\n",
535 	    progname, c);
536 	usage();
537 }
538 
539 /*-
540  * Main_ParseArgLine --
541  *  	Used by the parse module when a .MFLAGS or .MAKEFLAGS target
542  *	is encountered and by main() when reading the .MAKEFLAGS envariable.
543  *	Takes a line of arguments and breaks it into its
544  * 	component words and passes those words and the number of them to the
545  *	MainParseArgs function.
546  *	The line should have all its leading whitespace removed.
547  *
548  * Input:
549  *	line		Line to fracture
550  *
551  * Results:
552  *	None
553  *
554  * Side Effects:
555  *	Only those that come from the various arguments.
556  */
557 void
558 Main_ParseArgLine(char *line)
559 {
560 	char **argv;			/* Manufactured argument vector */
561 	int argc;			/* Number of arguments in argv */
562 	char *args;			/* Space used by the args */
563 	char *buf, *p1;
564 	char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
565 	size_t len;
566 
567 	if (line == NULL)
568 		return;
569 	for (; *line == ' '; ++line)
570 		continue;
571 	if (!*line)
572 		return;
573 
574 	buf = emalloc(len = strlen(line) + strlen(argv0) + 2);
575 	(void)snprintf(buf, len, "%s %s", argv0, line);
576 	if (p1)
577 		free(p1);
578 
579 	argv = brk_string(buf, &argc, TRUE, &args);
580 	free(buf);
581 	MainParseArgs(argc, argv);
582 
583 	free(args);
584 	free(argv);
585 }
586 
587 Boolean
588 Main_SetObjdir(const char *path)
589 {
590 	struct stat sb;
591 	char *p = NULL;
592 	char buf[MAXPATHLEN + 1];
593 	Boolean rc = FALSE;
594 
595 	/* expand variable substitutions */
596 	if (strchr(path, '$') != 0) {
597 		snprintf(buf, MAXPATHLEN, "%s", path);
598 		path = p = Var_Subst(NULL, buf, VAR_GLOBAL, 0);
599 	}
600 
601 	if (path[0] != '/') {
602 		snprintf(buf, MAXPATHLEN, "%s/%s", curdir, path);
603 		path = buf;
604 	}
605 
606 	/* look for the directory and try to chdir there */
607 	if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
608 		if (chdir(path)) {
609 			(void)fprintf(stderr, "make warning: %s: %s.\n",
610 				      path, strerror(errno));
611 		} else {
612 			strncpy(objdir, path, MAXPATHLEN);
613 			Var_Set(".OBJDIR", objdir, VAR_GLOBAL, 0);
614 			setenv("PWD", objdir, 1);
615 			Dir_InitDot();
616 			rc = TRUE;
617 		}
618 	}
619 
620 	if (p)
621 		free(p);
622 	return rc;
623 }
624 
625 /*-
626  * ReadAllMakefiles --
627  *	wrapper around ReadMakefile() to read all.
628  *
629  * Results:
630  *	TRUE if ok, FALSE on error
631  */
632 static int
633 ReadAllMakefiles(ClientData p, ClientData q)
634 {
635 	return (ReadMakefile(p, q) == 0);
636 }
637 
638 /*-
639  * main --
640  *	The main function, for obvious reasons. Initializes variables
641  *	and a few modules, then parses the arguments give it in the
642  *	environment and on the command line. Reads the system makefile
643  *	followed by either Makefile, makefile or the file given by the
644  *	-f argument. Sets the .MAKEFLAGS PMake variable based on all the
645  *	flags it has received by then uses either the Make or the Compat
646  *	module to create the initial list of targets.
647  *
648  * Results:
649  *	If -q was given, exits -1 if anything was out-of-date. Else it exits
650  *	0.
651  *
652  * Side Effects:
653  *	The program exits when done. Targets are created. etc. etc. etc.
654  */
655 int
656 main(int argc, char **argv)
657 {
658 	Lst targs;	/* target nodes to create -- passed to Make_Init */
659 	Boolean outOfDate = TRUE; 	/* FALSE if all targets up to date */
660 	struct stat sb, sa;
661 	char *p1, *path, *pwd;
662 	char mdpath[MAXPATHLEN];
663     	char *machine = getenv("MACHINE");
664 	const char *machine_arch = getenv("MACHINE_ARCH");
665 	char *syspath = getenv("MAKESYSPATH");
666 	Lst sysMkPath;			/* Path of sys.mk */
667 	char *cp = NULL, *start;
668 					/* avoid faults on read-only strings */
669 	static char defsyspath[] = _PATH_DEFSYSPATH;
670 	char found_path[MAXPATHLEN + 1];	/* for searching for sys.mk */
671 	struct timeval rightnow;		/* to initialize random seed */
672 #ifdef MAKE_NATIVE
673 	struct utsname utsname;
674 #endif
675 
676 	/* default to writing debug to stdout */
677 	debug_file = stdout;
678 
679 	/*
680 	 * Set the seed to produce a different random sequences
681 	 * on each program execution.
682 	 */
683 	gettimeofday(&rightnow, NULL);
684 	srandom(rightnow.tv_sec + rightnow.tv_usec);
685 
686 	if ((progname = strrchr(argv[0], '/')) != NULL)
687 		progname++;
688 	else
689 		progname = argv[0];
690 #ifdef RLIMIT_NOFILE
691 	/*
692 	 * get rid of resource limit on file descriptors
693 	 */
694 	{
695 		struct rlimit rl;
696 		if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
697 		    rl.rlim_cur != rl.rlim_max) {
698 			rl.rlim_cur = rl.rlim_max;
699 			(void)setrlimit(RLIMIT_NOFILE, &rl);
700 		}
701 	}
702 #endif
703 	/*
704 	 * Find where we are and take care of PWD for the automounter...
705 	 * All this code is so that we know where we are when we start up
706 	 * on a different machine with pmake.
707 	 */
708 	if (getcwd(curdir, MAXPATHLEN) == NULL) {
709 		(void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
710 		exit(2);
711 	}
712 
713 	if (stat(curdir, &sa) == -1) {
714 	    (void)fprintf(stderr, "%s: %s: %s.\n",
715 		 progname, curdir, strerror(errno));
716 	    exit(2);
717 	}
718 
719 	/*
720 	 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
721 	 * since the value of curdir can very depending on how we got
722 	 * here.  Ie sitting at a shell prompt (shell that provides $PWD)
723 	 * or via subdir.mk in which case its likely a shell which does
724 	 * not provide it.
725 	 * So, to stop it breaking this case only, we ignore PWD if
726 	 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
727 	 */
728 	if ((pwd = getenv("PWD")) != NULL && getenv("MAKEOBJDIRPREFIX") == NULL) {
729 		const char *makeobjdir = getenv("MAKEOBJDIR");
730 
731 		if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
732 			if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
733 			    sa.st_dev == sb.st_dev)
734 				(void)strncpy(curdir, pwd, MAXPATHLEN);
735 		}
736 	}
737 
738 	/*
739 	 * Get the name of this type of MACHINE from utsname
740 	 * so we can share an executable for similar machines.
741 	 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
742 	 *
743 	 * Note that both MACHINE and MACHINE_ARCH are decided at
744 	 * run-time.
745 	 */
746 	if (!machine) {
747 #ifdef MAKE_NATIVE
748 	    if (uname(&utsname) == -1) {
749 		(void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
750 		    strerror(errno));
751 		exit(2);
752 	    }
753 	    machine = utsname.machine;
754 #else
755 #ifdef MAKE_MACHINE
756 	    machine = MAKE_MACHINE;
757 #else
758 	    machine = "unknown";
759 #endif
760 #endif
761 	}
762 
763 	if (!machine_arch) {
764 #ifndef MACHINE_ARCH
765 #ifdef MAKE_MACHINE_ARCH
766             machine_arch = MAKE_MACHINE_ARCH;
767 #else
768 	    machine_arch = "unknown";
769 #endif
770 #else
771 	    machine_arch = MACHINE_ARCH;
772 #endif
773 	}
774 
775 	/*
776 	 * Just in case MAKEOBJDIR wants us to do something tricky.
777 	 */
778 	Var_Init();		/* Initialize the lists of variables for
779 				 * parsing arguments */
780 	Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0);
781 	Var_Set("MACHINE", machine, VAR_GLOBAL, 0);
782 	Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL, 0);
783 #ifdef MAKE_VERSION
784 	Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL, 0);
785 #endif
786 	Var_Set(".newline", "\n", VAR_GLOBAL, 0); /* handy for :@ loops */
787 
788 	/*
789 	 * Find the .OBJDIR.  If MAKEOBJDIRPREFIX, or failing that,
790 	 * MAKEOBJDIR is set in the environment, try only that value
791 	 * and fall back to .CURDIR if it does not exist.
792 	 *
793 	 * Otherwise, try _PATH_OBJDIR.MACHINE, _PATH_OBJDIR, and
794 	 * finally _PATH_OBJDIRPREFIX`pwd`, in that order.  If none
795 	 * of these paths exist, just use .CURDIR.
796 	 */
797 	Dir_Init(curdir);
798 	(void)Main_SetObjdir(curdir);
799 
800 	if ((path = getenv("MAKEOBJDIRPREFIX")) != NULL) {
801 		(void)snprintf(mdpath, MAXPATHLEN, "%s%s", path, curdir);
802 		(void)Main_SetObjdir(mdpath);
803 	} else if ((path = getenv("MAKEOBJDIR")) != NULL) {
804 		(void)Main_SetObjdir(path);
805 	} else {
806 		(void)snprintf(mdpath, MAXPATHLEN, "%s.%s", _PATH_OBJDIR, machine);
807 		if (!Main_SetObjdir(mdpath) && !Main_SetObjdir(_PATH_OBJDIR)) {
808 			(void)snprintf(mdpath, MAXPATHLEN, "%s%s",
809 					_PATH_OBJDIRPREFIX, curdir);
810 			(void)Main_SetObjdir(mdpath);
811 		}
812 	}
813 
814 	create = Lst_Init(FALSE);
815 	makefiles = Lst_Init(FALSE);
816 	printVars = FALSE;
817 	variables = Lst_Init(FALSE);
818 	beSilent = FALSE;		/* Print commands as executed */
819 	ignoreErrors = FALSE;		/* Pay attention to non-zero returns */
820 	noExecute = FALSE;		/* Execute all commands */
821 	noRecursiveExecute = FALSE;	/* Execute all .MAKE targets */
822 	keepgoing = FALSE;		/* Stop on error */
823 	allPrecious = FALSE;		/* Remove targets when interrupted */
824 	queryFlag = FALSE;		/* This is not just a check-run */
825 	noBuiltins = FALSE;		/* Read the built-in rules */
826 	touchFlag = FALSE;		/* Actually update targets */
827 	debug = 0;			/* No debug verbosity, please. */
828 	jobsRunning = FALSE;
829 
830 	maxJobs = DEFMAXLOCAL;		/* Set default local max concurrency */
831 	maxJobTokens = maxJobs;
832 	compatMake = FALSE;		/* No compat mode */
833 
834 
835 	/*
836 	 * Initialize the parsing, directory and variable modules to prepare
837 	 * for the reading of inclusion paths and variable settings on the
838 	 * command line
839 	 */
840 
841 	/*
842 	 * Initialize various variables.
843 	 *	MAKE also gets this name, for compatibility
844 	 *	.MAKEFLAGS gets set to the empty string just in case.
845 	 *	MFLAGS also gets initialized empty, for compatibility.
846 	 */
847 	Parse_Init();
848 	Var_Set("MAKE", argv[0], VAR_GLOBAL, 0);
849 	Var_Set(".MAKE", argv[0], VAR_GLOBAL, 0);
850 	Var_Set(MAKEFLAGS, "", VAR_GLOBAL, 0);
851 	Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL, 0);
852 	Var_Set("MFLAGS", "", VAR_GLOBAL, 0);
853 	Var_Set(".ALLTARGETS", "", VAR_GLOBAL, 0);
854 
855 	/*
856 	 * First snag any flags out of the MAKE environment variable.
857 	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
858 	 * in a different format).
859 	 */
860 #ifdef POSIX
861 	Main_ParseArgLine(getenv("MAKEFLAGS"));
862 #else
863 	Main_ParseArgLine(getenv("MAKE"));
864 #endif
865 
866 	MainParseArgs(argc, argv);
867 
868 	/*
869 	 * Be compatible if user did not specify -j and did not explicitly
870 	 * turned compatibility on
871 	 */
872 	if (!compatMake && !forceJobs) {
873 		compatMake = TRUE;
874 	}
875 
876 	/*
877 	 * Initialize archive, target and suffix modules in preparation for
878 	 * parsing the makefile(s)
879 	 */
880 	Arch_Init();
881 	Targ_Init();
882 	Suff_Init();
883 	Trace_Init(tracefile);
884 
885 	DEFAULT = NILGNODE;
886 	(void)time(&now);
887 
888 	Trace_Log(MAKESTART, NULL);
889 
890 	/*
891 	 * Set up the .TARGETS variable to contain the list of targets to be
892 	 * created. If none specified, make the variable empty -- the parser
893 	 * will fill the thing in with the default or .MAIN target.
894 	 */
895 	if (!Lst_IsEmpty(create)) {
896 		LstNode ln;
897 
898 		for (ln = Lst_First(create); ln != NILLNODE;
899 		    ln = Lst_Succ(ln)) {
900 			char *name = (char *)Lst_Datum(ln);
901 
902 			Var_Append(".TARGETS", name, VAR_GLOBAL);
903 		}
904 	} else
905 		Var_Set(".TARGETS", "", VAR_GLOBAL, 0);
906 
907 
908 	/*
909 	 * If no user-supplied system path was given (through the -m option)
910 	 * add the directories from the DEFSYSPATH (more than one may be given
911 	 * as dir1:...:dirn) to the system include path.
912 	 */
913 	if (syspath == NULL || *syspath == '\0')
914 		syspath = defsyspath;
915 	else
916 		syspath = strdup(syspath);
917 
918 	for (start = syspath; *start != '\0'; start = cp) {
919 		for (cp = start; *cp != '\0' && *cp != ':'; cp++)
920 			continue;
921 		if (*cp == ':') {
922 			*cp++ = '\0';
923 		}
924 		/* look for magic parent directory search string */
925 		if (strncmp(".../", start, 4) != 0) {
926 			(void)Dir_AddDir(defIncPath, start);
927 		} else {
928 			if (Dir_FindHereOrAbove(curdir, start+4,
929 			    found_path, sizeof(found_path))) {
930 				(void)Dir_AddDir(defIncPath, found_path);
931 			}
932 		}
933 	}
934 	if (syspath != defsyspath)
935 		free(syspath);
936 
937 	/*
938 	 * Read in the built-in rules first, followed by the specified
939 	 * makefile, if it was (makefile != NULL), or the default
940 	 * makefile and Makefile, in that order, if it wasn't.
941 	 */
942 	if (!noBuiltins) {
943 		LstNode ln;
944 
945 		sysMkPath = Lst_Init(FALSE);
946 		Dir_Expand(_PATH_DEFSYSMK,
947 			   Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
948 			   sysMkPath);
949 		if (Lst_IsEmpty(sysMkPath))
950 			Fatal("%s: no system rules (%s).", progname,
951 			    _PATH_DEFSYSMK);
952 		ln = Lst_Find(sysMkPath, (ClientData)NULL, ReadMakefile);
953 		if (ln == NILLNODE)
954 			Fatal("%s: cannot open %s.", progname,
955 			    (char *)Lst_Datum(ln));
956 	}
957 
958 	if (!Lst_IsEmpty(makefiles)) {
959 		LstNode ln;
960 
961 		ln = Lst_Find(makefiles, (ClientData)NULL, ReadAllMakefiles);
962 		if (ln != NILLNODE)
963 			Fatal("%s: cannot open %s.", progname,
964 			    (char *)Lst_Datum(ln));
965 	} else if (ReadMakefile(UNCONST("makefile"), NULL) != 0)
966 		(void)ReadMakefile(UNCONST("Makefile"), NULL);
967 
968 	(void)ReadMakefile(UNCONST(".depend"), NULL);
969 
970 	Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
971 	if (p1)
972 	    free(p1);
973 
974 	if (!compatMake)
975 	    Job_ServerStart(maxJobTokens, jp_0, jp_1);
976 	if (DEBUG(JOB))
977 	    fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
978 		jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
979 
980 	Main_ExportMAKEFLAGS(TRUE);	/* initial export */
981 
982 	Check_Cwd_av(0, NULL, 0);	/* initialize it */
983 
984 
985 	/*
986 	 * For compatibility, look at the directories in the VPATH variable
987 	 * and add them to the search path, if the variable is defined. The
988 	 * variable's value is in the same format as the PATH envariable, i.e.
989 	 * <directory>:<directory>:<directory>...
990 	 */
991 	if (Var_Exists("VPATH", VAR_CMD)) {
992 		char *vpath, savec;
993 		/*
994 		 * GCC stores string constants in read-only memory, but
995 		 * Var_Subst will want to write this thing, so store it
996 		 * in an array
997 		 */
998 		static char VPATH[] = "${VPATH}";
999 
1000 		vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
1001 		path = vpath;
1002 		do {
1003 			/* skip to end of directory */
1004 			for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1005 				continue;
1006 			/* Save terminator character so know when to stop */
1007 			savec = *cp;
1008 			*cp = '\0';
1009 			/* Add directory to search path */
1010 			(void)Dir_AddDir(dirSearchPath, path);
1011 			*cp = savec;
1012 			path = cp + 1;
1013 		} while (savec == ':');
1014 		free(vpath);
1015 	}
1016 
1017 	/*
1018 	 * Now that all search paths have been read for suffixes et al, it's
1019 	 * time to add the default search path to their lists...
1020 	 */
1021 	Suff_DoPaths();
1022 
1023 	/*
1024 	 * Propagate attributes through :: dependency lists.
1025 	 *
1026 	 * Also propagate recursive dependencies for .WAIT.
1027 	 */
1028 	Targ_Propagate();
1029 
1030 	/* print the initial graph, if the user requested it */
1031 	if (DEBUG(GRAPH1))
1032 		Targ_PrintGraph(1);
1033 
1034 	/* print the values of any variables requested by the user */
1035 	if (printVars) {
1036 		LstNode ln;
1037 
1038 		for (ln = Lst_First(variables); ln != NILLNODE;
1039 		    ln = Lst_Succ(ln)) {
1040 			char *var = (char *)Lst_Datum(ln);
1041 			char *value;
1042 
1043 			if (strchr(var, '$')) {
1044 				value = p1 = Var_Subst(NULL, var, VAR_GLOBAL, 0);
1045 			} else {
1046 				value = Var_Value(var, VAR_GLOBAL, &p1);
1047 			}
1048 			printf("%s\n", value ? value : "");
1049 			if (p1)
1050 				free(p1);
1051 		}
1052 	}
1053 
1054 	/*
1055 	 * Have now read the entire graph and need to make a list of targets
1056 	 * to create. If none was given on the command line, we consult the
1057 	 * parsing module to find the main target(s) to create.
1058 	 */
1059 	if (Lst_IsEmpty(create))
1060 		targs = Parse_MainName();
1061 	else
1062 		targs = Targ_FindList(create, TARG_CREATE);
1063 
1064 	if (!compatMake && !printVars) {
1065 		/*
1066 		 * Initialize job module before traversing the graph, now that
1067 		 * any .BEGIN and .END targets have been read.  This is done
1068 		 * only if the -q flag wasn't given (to prevent the .BEGIN from
1069 		 * being executed should it exist).
1070 		 */
1071 		if (!queryFlag) {
1072 			Job_Init();
1073 			jobsRunning = TRUE;
1074 		}
1075 
1076 		/* Traverse the graph, checking on all the targets */
1077 		outOfDate = Make_Run(targs);
1078 	} else if (!printVars) {
1079 		/*
1080 		 * Compat_Init will take care of creating all the targets as
1081 		 * well as initializing the module.
1082 		 */
1083 		Compat_Run(targs);
1084 	}
1085 
1086 #ifdef CLEANUP
1087 	Lst_Destroy(targs, NOFREE);
1088 	Lst_Destroy(variables, NOFREE);
1089 	Lst_Destroy(makefiles, NOFREE);
1090 	Lst_Destroy(create, (FreeProc *)free);
1091 #endif
1092 
1093 	/* print the graph now it's been processed if the user requested it */
1094 	if (DEBUG(GRAPH2))
1095 		Targ_PrintGraph(2);
1096 
1097 	Trace_Log(MAKEEND, 0);
1098 
1099 	Suff_End();
1100         Targ_End();
1101 	Arch_End();
1102 	Var_End();
1103 	Parse_End();
1104 	Dir_End();
1105 	Job_End();
1106 	Trace_End();
1107 
1108 	if (queryFlag && outOfDate)
1109 		return(1);
1110 	else
1111 		return(0);
1112 }
1113 
1114 /*-
1115  * ReadMakefile  --
1116  *	Open and parse the given makefile.
1117  *
1118  * Results:
1119  *	0 if ok. -1 if couldn't open file.
1120  *
1121  * Side Effects:
1122  *	lots
1123  */
1124 static int
1125 ReadMakefile(ClientData p, ClientData q __unused)
1126 {
1127 	char *fname = p;		/* makefile to read */
1128 	FILE *stream;
1129 	size_t len = MAXPATHLEN;
1130 	char *name, *path = emalloc(len);
1131 	int setMAKEFILE;
1132 
1133 	if (!strcmp(fname, "-")) {
1134 		Parse_File("(stdin)", stdin);
1135 		Var_Set("MAKEFILE", "", VAR_GLOBAL, 0);
1136 	} else {
1137 		setMAKEFILE = strcmp(fname, ".depend");
1138 
1139 		/* if we've chdir'd, rebuild the path name */
1140 		if (strcmp(curdir, objdir) && *fname != '/') {
1141 			size_t plen = strlen(curdir) + strlen(fname) + 2;
1142 			if (len < plen)
1143 				path = erealloc(path, len = 2 * plen);
1144 
1145 			(void)snprintf(path, len, "%s/%s", curdir, fname);
1146 			if ((stream = fopen(path, "r")) != NULL) {
1147 				fname = path;
1148 				goto found;
1149 			}
1150 
1151 			/* If curdir failed, try objdir (ala .depend) */
1152 			plen = strlen(objdir) + strlen(fname) + 2;
1153 			if (len < plen)
1154 				path = erealloc(path, len = 2 * plen);
1155 			(void)snprintf(path, len, "%s/%s", objdir, fname);
1156 			if ((stream = fopen(path, "r")) != NULL) {
1157 				fname = path;
1158 				goto found;
1159 			}
1160 		} else if ((stream = fopen(fname, "r")) != NULL)
1161 			goto found;
1162 		/* look in -I and system include directories. */
1163 		name = Dir_FindFile(fname, parseIncPath);
1164 		if (!name)
1165 			name = Dir_FindFile(fname,
1166 				Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1167 		if (!name || (stream = fopen(name, "r")) == NULL) {
1168 			if (name)
1169 				free(name);
1170 			free(path);
1171 			return(-1);
1172 		}
1173 		fname = name;
1174 		/*
1175 		 * set the MAKEFILE variable desired by System V fans -- the
1176 		 * placement of the setting here means it gets set to the last
1177 		 * makefile specified, as it is set by SysV make.
1178 		 */
1179 found:
1180 		if (setMAKEFILE)
1181 			Var_Set("MAKEFILE", fname, VAR_GLOBAL, 0);
1182 		Parse_File(fname, stream);
1183 		(void)fclose(stream);
1184 	}
1185 	free(path);
1186 	return(0);
1187 }
1188 
1189 
1190 /*
1191  * If MAKEOBJDIRPREFIX is in use, make ends up not in .CURDIR
1192  * in situations that would not arrise with ./obj (links or not).
1193  * This tends to break things like:
1194  *
1195  * build:
1196  * 	${MAKE} includes
1197  *
1198  * This function spots when ${.MAKE:T} or ${.MAKE} is a command (as
1199  * opposed to an argument) in a command line and if so returns
1200  * ${.CURDIR} so caller can chdir() so that the assumptions made by
1201  * the Makefile hold true.
1202  *
1203  * If ${.MAKE} does not contain any '/', then ${.MAKE:T} is skipped.
1204  *
1205  * The chdir() only happens in the child process, and does nothing if
1206  * MAKEOBJDIRPREFIX and MAKEOBJDIR are not in the environment so it
1207  * should not break anything.  Also if NOCHECKMAKECHDIR is set we
1208  * do nothing - to ensure historic semantics can be retained.
1209  */
1210 static int  Check_Cwd_Off = 0;
1211 
1212 static char *
1213 Check_Cwd_av(int ac, char **av, int copy)
1214 {
1215     static char *make[4];
1216     static char *cur_dir = NULL;
1217     char **mp;
1218     char *cp;
1219     int is_cmd, next_cmd;
1220     int i;
1221     int n;
1222 
1223     if (Check_Cwd_Off)
1224 	return NULL;
1225 
1226     if (make[0] == NULL) {
1227 	if (Var_Exists("NOCHECKMAKECHDIR", VAR_GLOBAL)) {
1228 	    Check_Cwd_Off = 1;
1229 	    return NULL;
1230 	}
1231 
1232         make[1] = Var_Value(".MAKE", VAR_GLOBAL, &cp);
1233         if ((make[0] = strrchr(make[1], '/')) == NULL) {
1234             make[0] = make[1];
1235             make[1] = NULL;
1236         } else
1237             ++make[0];
1238         make[2] = NULL;
1239         cur_dir = Var_Value(".CURDIR", VAR_GLOBAL, &cp);
1240     }
1241     if (ac == 0 || av == NULL)
1242         return NULL;			/* initialization only */
1243 
1244     if (getenv("MAKEOBJDIR") == NULL &&
1245         getenv("MAKEOBJDIRPREFIX") == NULL)
1246         return NULL;
1247 
1248 
1249     next_cmd = 1;
1250     for (i = 0; i < ac; ++i) {
1251 	is_cmd = next_cmd;
1252 
1253 	n = strlen(av[i]);
1254 	cp = &(av[i])[n - 1];
1255 	if (strspn(av[i], "|&;") == (size_t)n) {
1256 	    next_cmd = 1;
1257 	    continue;
1258 	} else if (*cp == ';' || *cp == '&' || *cp == '|' || *cp == ')') {
1259 	    next_cmd = 1;
1260 	    if (copy) {
1261 		do {
1262 		    *cp-- = '\0';
1263 		} while (*cp == ';' || *cp == '&' || *cp == '|' ||
1264 			 *cp == ')' || *cp == '}') ;
1265 	    } else {
1266 		/*
1267 		 * XXX this should not happen.
1268 		 */
1269 		fprintf(stderr, "WARNING: raw arg ends in shell meta '%s'\n",
1270 			av[i]);
1271 	    }
1272 	} else
1273 	    next_cmd = 0;
1274 
1275 	cp = av[i];
1276 	if (*cp == ';' || *cp == '&' || *cp == '|')
1277 	    is_cmd = 1;
1278 
1279 #ifdef check_cwd_debug
1280 	fprintf(stderr, "av[%d] == %s '%s'",
1281 		i, (is_cmd) ? "cmd" : "arg", av[i]);
1282 #endif
1283 	if (is_cmd != 0) {
1284 	    if (*cp == '(' || *cp == '{' ||
1285 		*cp == ';' || *cp == '&' || *cp == '|') {
1286 		do {
1287 		    ++cp;
1288 		} while (*cp == '(' || *cp == '{' ||
1289 			 *cp == ';' || *cp == '&' || *cp == '|');
1290 		if (*cp == '\0') {
1291 		    next_cmd = 1;
1292 		    continue;
1293 		}
1294 	    }
1295 	    if (strcmp(cp, "cd") == 0 || strcmp(cp, "chdir") == 0) {
1296 #ifdef check_cwd_debug
1297 		fprintf(stderr, " == cd, done.\n");
1298 #endif
1299 		return NULL;
1300 	    }
1301 	    for (mp = make; *mp != NULL; ++mp) {
1302 		n = strlen(*mp);
1303 		if (strcmp(cp, *mp) == 0) {
1304 #ifdef check_cwd_debug
1305 		    fprintf(stderr, " %s == '%s', chdir(%s)\n",
1306 			    cp, *mp, cur_dir);
1307 #endif
1308 		    return cur_dir;
1309 		}
1310 	    }
1311 	}
1312 #ifdef check_cwd_debug
1313 	fprintf(stderr, "\n");
1314 #endif
1315     }
1316     return NULL;
1317 }
1318 
1319 char *
1320 Check_Cwd_Cmd(const char *cmd)
1321 {
1322     char *cp, *bp;
1323     char **av;
1324     int ac;
1325 
1326     if (Check_Cwd_Off)
1327 	return NULL;
1328 
1329     if (cmd) {
1330 	av = brk_string(cmd, &ac, TRUE, &bp);
1331 #ifdef check_cwd_debug
1332 	fprintf(stderr, "splitting: '%s' -> %d words\n",
1333 		cmd, ac);
1334 #endif
1335     } else {
1336 	ac = 0;
1337 	av = NULL;
1338 	bp = NULL;
1339     }
1340     cp = Check_Cwd_av(ac, av, 1);
1341     if (bp)
1342 	free(bp);
1343     if (av)
1344 	free(av);
1345     return cp;
1346 }
1347 
1348 void
1349 Check_Cwd(const char **argv)
1350 {
1351     char *cp;
1352     int ac;
1353 
1354     if (Check_Cwd_Off)
1355 	return;
1356 
1357     for (ac = 0; argv[ac] != NULL; ++ac)
1358 	/* NOTHING */;
1359     if (ac == 3 && *argv[1] == '-') {
1360 	cp =  Check_Cwd_Cmd(argv[2]);
1361     } else {
1362 	cp = Check_Cwd_av(ac, UNCONST(argv), 0);
1363     }
1364     if (cp) {
1365 	chdir(cp);
1366     }
1367 }
1368 
1369 /*-
1370  * Cmd_Exec --
1371  *	Execute the command in cmd, and return the output of that command
1372  *	in a string.
1373  *
1374  * Results:
1375  *	A string containing the output of the command, or the empty string
1376  *	If errnum is not NULL, it contains the reason for the command failure
1377  *
1378  * Side Effects:
1379  *	The string must be freed by the caller.
1380  */
1381 char *
1382 Cmd_Exec(const char *cmd, const char **errnum)
1383 {
1384     const char	*args[4];   	/* Args for invoking the shell */
1385     int 	fds[2];	    	/* Pipe streams */
1386     int 	cpid;	    	/* Child PID */
1387     int 	pid;	    	/* PID from wait() */
1388     char	*res;		/* result */
1389     int		status;		/* command exit status */
1390     Buffer	buf;		/* buffer to store the result */
1391     char	*cp;
1392     int		cc;
1393 
1394 
1395     *errnum = NULL;
1396 
1397     if (!shellName)
1398 	Shell_Init();
1399     /*
1400      * Set up arguments for shell
1401      */
1402     args[0] = shellName;
1403     args[1] = "-c";
1404     args[2] = cmd;
1405     args[3] = NULL;
1406 
1407     /*
1408      * Open a pipe for fetching its output
1409      */
1410     if (pipe(fds) == -1) {
1411 	*errnum = "Couldn't create pipe for \"%s\"";
1412 	goto bad;
1413     }
1414 
1415     /*
1416      * Fork
1417      */
1418     switch (cpid = vfork()) {
1419     case 0:
1420 	/*
1421 	 * Close input side of pipe
1422 	 */
1423 	(void)close(fds[0]);
1424 
1425 	/*
1426 	 * Duplicate the output stream to the shell's output, then
1427 	 * shut the extra thing down. Note we don't fetch the error
1428 	 * stream...why not? Why?
1429 	 */
1430 	(void)dup2(fds[1], 1);
1431 	(void)close(fds[1]);
1432 
1433 	(void)execv(shellPath, UNCONST(args));
1434 	_exit(1);
1435 	/*NOTREACHED*/
1436 
1437     case -1:
1438 	*errnum = "Couldn't exec \"%s\"";
1439 	goto bad;
1440 
1441     default:
1442 	/*
1443 	 * No need for the writing half
1444 	 */
1445 	(void)close(fds[1]);
1446 
1447 	buf = Buf_Init(MAKE_BSIZE);
1448 
1449 	do {
1450 	    char   result[BUFSIZ];
1451 	    cc = read(fds[0], result, sizeof(result));
1452 	    if (cc > 0)
1453 		Buf_AddBytes(buf, cc, (Byte *)result);
1454 	}
1455 	while (cc > 0 || (cc == -1 && errno == EINTR));
1456 
1457 	/*
1458 	 * Close the input side of the pipe.
1459 	 */
1460 	(void)close(fds[0]);
1461 
1462 	/*
1463 	 * Wait for the process to exit.
1464 	 */
1465 	while(((pid = wait(&status)) != cpid) && (pid >= 0))
1466 	    continue;
1467 
1468 	res = (char *)Buf_GetAll(buf, &cc);
1469 	Buf_Destroy(buf, FALSE);
1470 
1471 	if (cc == 0)
1472 	    *errnum = "Couldn't read shell's output for \"%s\"";
1473 
1474 	if (status)
1475 	    *errnum = "\"%s\" returned non-zero status";
1476 
1477 	/*
1478 	 * Null-terminate the result, convert newlines to spaces and
1479 	 * install it in the variable.
1480 	 */
1481 	res[cc] = '\0';
1482 	cp = &res[cc];
1483 
1484 	if (cc > 0 && *--cp == '\n') {
1485 	    /*
1486 	     * A final newline is just stripped
1487 	     */
1488 	    *cp-- = '\0';
1489 	}
1490 	while (cp >= res) {
1491 	    if (*cp == '\n') {
1492 		*cp = ' ';
1493 	    }
1494 	    cp--;
1495 	}
1496 	break;
1497     }
1498     return res;
1499 bad:
1500     res = emalloc(1);
1501     *res = '\0';
1502     return res;
1503 }
1504 
1505 /*-
1506  * Error --
1507  *	Print an error message given its format.
1508  *
1509  * Results:
1510  *	None.
1511  *
1512  * Side Effects:
1513  *	The message is printed.
1514  */
1515 /* VARARGS */
1516 void
1517 Error(const char *fmt, ...)
1518 {
1519 	va_list ap;
1520 
1521 	va_start(ap, fmt);
1522 	fprintf(stderr, "%s: ", progname);
1523 	(void)vfprintf(stderr, fmt, ap);
1524 	va_end(ap);
1525 	(void)fprintf(stderr, "\n");
1526 	(void)fflush(stderr);
1527 }
1528 
1529 /*-
1530  * Fatal --
1531  *	Produce a Fatal error message. If jobs are running, waits for them
1532  *	to finish.
1533  *
1534  * Results:
1535  *	None
1536  *
1537  * Side Effects:
1538  *	The program exits
1539  */
1540 /* VARARGS */
1541 void
1542 Fatal(const char *fmt, ...)
1543 {
1544 	va_list ap;
1545 
1546 	va_start(ap, fmt);
1547 	if (jobsRunning)
1548 		Job_Wait();
1549 
1550 	(void)vfprintf(stderr, fmt, ap);
1551 	va_end(ap);
1552 	(void)fprintf(stderr, "\n");
1553 	(void)fflush(stderr);
1554 
1555 	PrintOnError(NULL);
1556 
1557 	if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1558 		Targ_PrintGraph(2);
1559 	Trace_Log(MAKEERROR, 0);
1560 	exit(2);		/* Not 1 so -q can distinguish error */
1561 }
1562 
1563 /*
1564  * Punt --
1565  *	Major exception once jobs are being created. Kills all jobs, prints
1566  *	a message and exits.
1567  *
1568  * Results:
1569  *	None
1570  *
1571  * Side Effects:
1572  *	All children are killed indiscriminately and the program Lib_Exits
1573  */
1574 /* VARARGS */
1575 void
1576 Punt(const char *fmt, ...)
1577 {
1578 	va_list ap;
1579 
1580 	va_start(ap, fmt);
1581 	(void)fprintf(stderr, "%s: ", progname);
1582 	(void)vfprintf(stderr, fmt, ap);
1583 	va_end(ap);
1584 	(void)fprintf(stderr, "\n");
1585 	(void)fflush(stderr);
1586 
1587 	PrintOnError(NULL);
1588 
1589 	DieHorribly();
1590 }
1591 
1592 /*-
1593  * DieHorribly --
1594  *	Exit without giving a message.
1595  *
1596  * Results:
1597  *	None
1598  *
1599  * Side Effects:
1600  *	A big one...
1601  */
1602 void
1603 DieHorribly(void)
1604 {
1605 	if (jobsRunning)
1606 		Job_AbortAll();
1607 	if (DEBUG(GRAPH2))
1608 		Targ_PrintGraph(2);
1609 	Trace_Log(MAKEERROR, 0);
1610 	exit(2);		/* Not 1, so -q can distinguish error */
1611 }
1612 
1613 /*
1614  * Finish --
1615  *	Called when aborting due to errors in child shell to signal
1616  *	abnormal exit.
1617  *
1618  * Results:
1619  *	None
1620  *
1621  * Side Effects:
1622  *	The program exits
1623  */
1624 void
1625 Finish(int errors)
1626 	           	/* number of errors encountered in Make_Make */
1627 {
1628 	Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1629 }
1630 
1631 #ifndef MAKE_NATIVE
1632 /*
1633  * emalloc --
1634  *	malloc, but die on error.
1635  */
1636 void *
1637 emalloc(size_t len)
1638 {
1639 	void *p;
1640 
1641 	if ((p = malloc(len)) == NULL)
1642 		enomem();
1643 	return(p);
1644 }
1645 
1646 /*
1647  * estrdup --
1648  *	strdup, but die on error.
1649  */
1650 char *
1651 estrdup(const char *str)
1652 {
1653 	char *p;
1654 
1655 	if ((p = strdup(str)) == NULL)
1656 		enomem();
1657 	return(p);
1658 }
1659 
1660 /*
1661  * erealloc --
1662  *	realloc, but die on error.
1663  */
1664 void *
1665 erealloc(void *ptr, size_t size)
1666 {
1667 	if ((ptr = realloc(ptr, size)) == NULL)
1668 		enomem();
1669 	return(ptr);
1670 }
1671 
1672 /*
1673  * enomem --
1674  *	die when out of memory.
1675  */
1676 void
1677 enomem(void)
1678 {
1679 	(void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
1680 	exit(2);
1681 }
1682 #endif
1683 
1684 /*
1685  * enunlink --
1686  *	Remove a file carefully, avoiding directories.
1687  */
1688 int
1689 eunlink(const char *file)
1690 {
1691 	struct stat st;
1692 
1693 	if (lstat(file, &st) == -1)
1694 		return -1;
1695 
1696 	if (S_ISDIR(st.st_mode)) {
1697 		errno = EISDIR;
1698 		return -1;
1699 	}
1700 	return unlink(file);
1701 }
1702 
1703 /*
1704  * execError --
1705  *	Print why exec failed, avoiding stdio.
1706  */
1707 void
1708 execError(const char *af, const char *av)
1709 {
1710 #ifdef USE_IOVEC
1711 	int i = 0;
1712 	struct iovec iov[8];
1713 #define IOADD(s) \
1714 	(void)(iov[i].iov_base = UNCONST(s), \
1715 	    iov[i].iov_len = strlen(iov[i].iov_base), \
1716 	    i++)
1717 #else
1718 #define	IOADD(void)write(2, s, strlen(s))
1719 #endif
1720 
1721 	IOADD(progname);
1722 	IOADD(": ");
1723 	IOADD(af);
1724 	IOADD("(");
1725 	IOADD(av);
1726 	IOADD(") failed (");
1727 	IOADD(strerror(errno));
1728 	IOADD(")\n");
1729 
1730 #ifdef USE_IOVEC
1731 	(void)writev(2, iov, 8);
1732 #endif
1733 }
1734 
1735 /*
1736  * usage --
1737  *	exit with usage message
1738  */
1739 static void
1740 usage(void)
1741 {
1742 	(void)fprintf(stderr,
1743 "usage: %s [-BeikNnqrstWX] [-D variable] [-d flags] [-f makefile]\n\
1744             [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1745             [-V variable] [variable=value] [target ...]\n", progname);
1746 	exit(2);
1747 }
1748 
1749 
1750 int
1751 PrintAddr(ClientData a, ClientData b)
1752 {
1753     printf("%lx ", (unsigned long) a);
1754     return b ? 0 : 0;
1755 }
1756 
1757 
1758 
1759 void
1760 PrintOnError(const char *s)
1761 {
1762     char tmp[64];
1763     char *cp;
1764 
1765     if (s)
1766 	    printf("%s", s);
1767 
1768     printf("\n%s: stopped in %s\n", progname, curdir);
1769     strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1770 	    sizeof(tmp) - 1);
1771     cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1772     if (cp) {
1773 	    if (*cp)
1774 		    printf("%s", cp);
1775 	    free(cp);
1776     }
1777 }
1778 
1779 void
1780 Main_ExportMAKEFLAGS(Boolean first)
1781 {
1782     static int once = 1;
1783     char tmp[64];
1784     char *s;
1785 
1786     if (once != first)
1787 	return;
1788     once = 0;
1789 
1790     strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1791 	    sizeof(tmp));
1792     s = Var_Subst(NULL, tmp, VAR_CMD, 0);
1793     if (s && *s) {
1794 #ifdef POSIX
1795 	setenv("MAKEFLAGS", s, 1);
1796 #else
1797 	setenv("MAKE", s, 1);
1798 #endif
1799     }
1800 }
1801