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