xref: /netbsd-src/usr.bin/make/main.c (revision 8b0f9554ff8762542c4defc4f70e1eb76fb508fa)
1 /*	$NetBSD: main.c,v 1.144 2007/10/13 16:16:41 apb 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.144 2007/10/13 16:16:41 apb 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.144 2007/10/13 16:16:41 apb 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\n",
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 	 * Set some other useful macros
870 	 */
871 	{
872 	    char tmp[64];
873 
874 	    snprintf(tmp, sizeof(tmp), "%u", getpid());
875 	    Var_Set(".MAKE.PID", tmp, VAR_GLOBAL, 0);
876 	    snprintf(tmp, sizeof(tmp), "%u", getppid());
877 	    Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL, 0);
878 	}
879 	Job_SetPrefix();
880 
881 	/*
882 	 * First snag any flags out of the MAKE environment variable.
883 	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
884 	 * in a different format).
885 	 */
886 #ifdef POSIX
887 	Main_ParseArgLine(getenv("MAKEFLAGS"));
888 #else
889 	Main_ParseArgLine(getenv("MAKE"));
890 #endif
891 
892 	MainParseArgs(argc, argv);
893 
894 	/*
895 	 * Be compatible if user did not specify -j and did not explicitly
896 	 * turned compatibility on
897 	 */
898 	if (!compatMake && !forceJobs) {
899 		compatMake = TRUE;
900 	}
901 
902 	/*
903 	 * Initialize archive, target and suffix modules in preparation for
904 	 * parsing the makefile(s)
905 	 */
906 	Arch_Init();
907 	Targ_Init();
908 	Suff_Init();
909 	Trace_Init(tracefile);
910 
911 	DEFAULT = NILGNODE;
912 	(void)time(&now);
913 
914 	Trace_Log(MAKESTART, NULL);
915 
916 	/*
917 	 * Set up the .TARGETS variable to contain the list of targets to be
918 	 * created. If none specified, make the variable empty -- the parser
919 	 * will fill the thing in with the default or .MAIN target.
920 	 */
921 	if (!Lst_IsEmpty(create)) {
922 		LstNode ln;
923 
924 		for (ln = Lst_First(create); ln != NILLNODE;
925 		    ln = Lst_Succ(ln)) {
926 			char *name = (char *)Lst_Datum(ln);
927 
928 			Var_Append(".TARGETS", name, VAR_GLOBAL);
929 		}
930 	} else
931 		Var_Set(".TARGETS", "", VAR_GLOBAL, 0);
932 
933 
934 	/*
935 	 * If no user-supplied system path was given (through the -m option)
936 	 * add the directories from the DEFSYSPATH (more than one may be given
937 	 * as dir1:...:dirn) to the system include path.
938 	 */
939 	if (syspath == NULL || *syspath == '\0')
940 		syspath = defsyspath;
941 	else
942 		syspath = estrdup(syspath);
943 
944 	for (start = syspath; *start != '\0'; start = cp) {
945 		for (cp = start; *cp != '\0' && *cp != ':'; cp++)
946 			continue;
947 		if (*cp == ':') {
948 			*cp++ = '\0';
949 		}
950 		/* look for magic parent directory search string */
951 		if (strncmp(".../", start, 4) != 0) {
952 			(void)Dir_AddDir(defIncPath, start);
953 		} else {
954 			if (Dir_FindHereOrAbove(curdir, start+4,
955 			    found_path, sizeof(found_path))) {
956 				(void)Dir_AddDir(defIncPath, found_path);
957 			}
958 		}
959 	}
960 	if (syspath != defsyspath)
961 		free(syspath);
962 
963 	/*
964 	 * Read in the built-in rules first, followed by the specified
965 	 * makefile, if it was (makefile != NULL), or the default
966 	 * makefile and Makefile, in that order, if it wasn't.
967 	 */
968 	if (!noBuiltins) {
969 		LstNode ln;
970 
971 		sysMkPath = Lst_Init(FALSE);
972 		Dir_Expand(_PATH_DEFSYSMK,
973 			   Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
974 			   sysMkPath);
975 		if (Lst_IsEmpty(sysMkPath))
976 			Fatal("%s: no system rules (%s).", progname,
977 			    _PATH_DEFSYSMK);
978 		ln = Lst_Find(sysMkPath, NULL, ReadMakefile);
979 		if (ln == NILLNODE)
980 			Fatal("%s: cannot open %s.", progname,
981 			    (char *)Lst_Datum(ln));
982 	}
983 
984 	if (!Lst_IsEmpty(makefiles)) {
985 		LstNode ln;
986 
987 		ln = Lst_Find(makefiles, NULL, ReadAllMakefiles);
988 		if (ln != NILLNODE)
989 			Fatal("%s: cannot open %s.", progname,
990 			    (char *)Lst_Datum(ln));
991 	} else if (ReadMakefile(UNCONST("makefile"), NULL) != 0)
992 		(void)ReadMakefile(UNCONST("Makefile"), NULL);
993 
994 	/* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
995 	if (!noBuiltins || !printVars)
996 		(void)ReadMakefile(UNCONST(".depend"), NULL);
997 
998 	Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
999 	if (p1)
1000 	    free(p1);
1001 
1002 	if (!compatMake)
1003 	    Job_ServerStart(maxJobTokens, jp_0, jp_1);
1004 	if (DEBUG(JOB))
1005 	    fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1006 		jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
1007 
1008 	Main_ExportMAKEFLAGS(TRUE);	/* initial export */
1009 
1010 	Check_Cwd_av(0, NULL, 0);	/* initialize it */
1011 
1012 
1013 	/*
1014 	 * For compatibility, look at the directories in the VPATH variable
1015 	 * and add them to the search path, if the variable is defined. The
1016 	 * variable's value is in the same format as the PATH envariable, i.e.
1017 	 * <directory>:<directory>:<directory>...
1018 	 */
1019 	if (Var_Exists("VPATH", VAR_CMD)) {
1020 		char *vpath, savec;
1021 		/*
1022 		 * GCC stores string constants in read-only memory, but
1023 		 * Var_Subst will want to write this thing, so store it
1024 		 * in an array
1025 		 */
1026 		static char VPATH[] = "${VPATH}";
1027 
1028 		vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
1029 		path = vpath;
1030 		do {
1031 			/* skip to end of directory */
1032 			for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1033 				continue;
1034 			/* Save terminator character so know when to stop */
1035 			savec = *cp;
1036 			*cp = '\0';
1037 			/* Add directory to search path */
1038 			(void)Dir_AddDir(dirSearchPath, path);
1039 			*cp = savec;
1040 			path = cp + 1;
1041 		} while (savec == ':');
1042 		free(vpath);
1043 	}
1044 
1045 	/*
1046 	 * Now that all search paths have been read for suffixes et al, it's
1047 	 * time to add the default search path to their lists...
1048 	 */
1049 	Suff_DoPaths();
1050 
1051 	/*
1052 	 * Propagate attributes through :: dependency lists.
1053 	 */
1054 	Targ_Propagate();
1055 
1056 	/* print the initial graph, if the user requested it */
1057 	if (DEBUG(GRAPH1))
1058 		Targ_PrintGraph(1);
1059 
1060 	/* print the values of any variables requested by the user */
1061 	if (printVars) {
1062 		LstNode ln;
1063 
1064 		for (ln = Lst_First(variables); ln != NILLNODE;
1065 		    ln = Lst_Succ(ln)) {
1066 			char *var = (char *)Lst_Datum(ln);
1067 			char *value;
1068 
1069 			if (strchr(var, '$')) {
1070 				value = p1 = Var_Subst(NULL, var, VAR_GLOBAL, 0);
1071 			} else {
1072 				value = Var_Value(var, VAR_GLOBAL, &p1);
1073 			}
1074 			printf("%s\n", value ? value : "");
1075 			if (p1)
1076 				free(p1);
1077 		}
1078 	} else {
1079 		/*
1080 		 * Have now read the entire graph and need to make a list of
1081 		 * targets to create. If none was given on the command line,
1082 		 * we consult the parsing module to find the main target(s)
1083 		 * to create.
1084 		 */
1085 		if (Lst_IsEmpty(create))
1086 			targs = Parse_MainName();
1087 		else
1088 			targs = Targ_FindList(create, TARG_CREATE);
1089 
1090 		if (!compatMake) {
1091 			/*
1092 			 * Initialize job module before traversing the graph
1093 			 * now that any .BEGIN and .END targets have been read.
1094 			 * This is done only if the -q flag wasn't given
1095 			 * (to prevent the .BEGIN from being executed should
1096 			 * it exist).
1097 			 */
1098 			if (!queryFlag) {
1099 				Job_Init();
1100 				jobsRunning = TRUE;
1101 			}
1102 
1103 			/* Traverse the graph, checking on all the targets */
1104 			outOfDate = Make_Run(targs);
1105 		} else {
1106 			/*
1107 			 * Compat_Init will take care of creating all the
1108 			 * targets as well as initializing the module.
1109 			 */
1110 			Compat_Run(targs);
1111 		}
1112 	}
1113 
1114 #ifdef CLEANUP
1115 	Lst_Destroy(targs, NOFREE);
1116 	Lst_Destroy(variables, NOFREE);
1117 	Lst_Destroy(makefiles, NOFREE);
1118 	Lst_Destroy(create, (FreeProc *)free);
1119 #endif
1120 
1121 	/* print the graph now it's been processed if the user requested it */
1122 	if (DEBUG(GRAPH2))
1123 		Targ_PrintGraph(2);
1124 
1125 	Trace_Log(MAKEEND, 0);
1126 
1127 	Suff_End();
1128         Targ_End();
1129 	Arch_End();
1130 	Var_End();
1131 	Parse_End();
1132 	Dir_End();
1133 	Job_End();
1134 	Trace_End();
1135 
1136 	return outOfDate ? 1 : 0;
1137 }
1138 
1139 /*-
1140  * ReadMakefile  --
1141  *	Open and parse the given makefile.
1142  *
1143  * Results:
1144  *	0 if ok. -1 if couldn't open file.
1145  *
1146  * Side Effects:
1147  *	lots
1148  */
1149 static int
1150 ReadMakefile(ClientData p, ClientData q __unused)
1151 {
1152 	char *fname = p;		/* makefile to read */
1153 	int fd;
1154 	size_t len = MAXPATHLEN;
1155 	char *name, *path = emalloc(len);
1156 	int setMAKEFILE;
1157 
1158 	if (!strcmp(fname, "-")) {
1159 		Parse_File("(stdin)", dup(fileno(stdin)));
1160 		Var_Set("MAKEFILE", "", VAR_GLOBAL, 0);
1161 	} else {
1162 		setMAKEFILE = strcmp(fname, ".depend");
1163 
1164 		/* if we've chdir'd, rebuild the path name */
1165 		if (strcmp(curdir, objdir) && *fname != '/') {
1166 			size_t plen = strlen(curdir) + strlen(fname) + 2;
1167 			if (len < plen)
1168 				path = erealloc(path, len = 2 * plen);
1169 
1170 			(void)snprintf(path, len, "%s/%s", curdir, fname);
1171 			fd = open(path, O_RDONLY);
1172 			if (fd != -1) {
1173 				fname = path;
1174 				goto found;
1175 			}
1176 
1177 			/* If curdir failed, try objdir (ala .depend) */
1178 			plen = strlen(objdir) + strlen(fname) + 2;
1179 			if (len < plen)
1180 				path = erealloc(path, len = 2 * plen);
1181 			(void)snprintf(path, len, "%s/%s", objdir, fname);
1182 			fd = open(path, O_RDONLY);
1183 			if (fd != -1) {
1184 				fname = path;
1185 				goto found;
1186 			}
1187 		} else {
1188 			fd = open(fname, O_RDONLY);
1189 			if (fd != -1)
1190 				goto found;
1191 		}
1192 		/* look in -I and system include directories. */
1193 		name = Dir_FindFile(fname, parseIncPath);
1194 		if (!name)
1195 			name = Dir_FindFile(fname,
1196 				Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1197 		if (!name || (fd = open(name, O_RDONLY)) == -1) {
1198 			if (name)
1199 				free(name);
1200 			free(path);
1201 			return(-1);
1202 		}
1203 		fname = name;
1204 		/*
1205 		 * set the MAKEFILE variable desired by System V fans -- the
1206 		 * placement of the setting here means it gets set to the last
1207 		 * makefile specified, as it is set by SysV make.
1208 		 */
1209 found:
1210 		if (setMAKEFILE)
1211 			Var_Set("MAKEFILE", fname, VAR_GLOBAL, 0);
1212 		Parse_File(fname, fd);
1213 	}
1214 	free(path);
1215 	return(0);
1216 }
1217 
1218 
1219 /*
1220  * If MAKEOBJDIRPREFIX is in use, make ends up not in .CURDIR
1221  * in situations that would not arrise with ./obj (links or not).
1222  * This tends to break things like:
1223  *
1224  * build:
1225  * 	${MAKE} includes
1226  *
1227  * This function spots when ${.MAKE:T} or ${.MAKE} is a command (as
1228  * opposed to an argument) in a command line and if so returns
1229  * ${.CURDIR} so caller can chdir() so that the assumptions made by
1230  * the Makefile hold true.
1231  *
1232  * If ${.MAKE} does not contain any '/', then ${.MAKE:T} is skipped.
1233  *
1234  * The chdir() only happens in the child process, and does nothing if
1235  * MAKEOBJDIRPREFIX and MAKEOBJDIR are not in the environment so it
1236  * should not break anything.  Also if NOCHECKMAKECHDIR is set we
1237  * do nothing - to ensure historic semantics can be retained.
1238  */
1239 static int  Check_Cwd_Off = 0;
1240 
1241 static char *
1242 Check_Cwd_av(int ac, char **av, int copy)
1243 {
1244     static char *make[4];
1245     static char *cur_dir = NULL;
1246     char **mp;
1247     char *cp;
1248     int is_cmd, next_cmd;
1249     int i;
1250     int n;
1251 
1252     if (Check_Cwd_Off)
1253 	return NULL;
1254 
1255     if (make[0] == NULL) {
1256 	if (Var_Exists("NOCHECKMAKECHDIR", VAR_GLOBAL)) {
1257 	    Check_Cwd_Off = 1;
1258 	    return NULL;
1259 	}
1260 
1261         make[1] = Var_Value(".MAKE", VAR_GLOBAL, &cp);
1262         if ((make[0] = strrchr(make[1], '/')) == NULL) {
1263             make[0] = make[1];
1264             make[1] = NULL;
1265         } else
1266             ++make[0];
1267         make[2] = NULL;
1268         cur_dir = Var_Value(".CURDIR", VAR_GLOBAL, &cp);
1269     }
1270     if (ac == 0 || av == NULL)
1271         return NULL;			/* initialization only */
1272 
1273     if (getenv("MAKEOBJDIR") == NULL &&
1274         getenv("MAKEOBJDIRPREFIX") == NULL)
1275         return NULL;
1276 
1277 
1278     next_cmd = 1;
1279     for (i = 0; i < ac; ++i) {
1280 	is_cmd = next_cmd;
1281 
1282 	n = strlen(av[i]);
1283 	cp = &(av[i])[n - 1];
1284 	if (strspn(av[i], "|&;") == (size_t)n) {
1285 	    next_cmd = 1;
1286 	    continue;
1287 	} else if (*cp == ';' || *cp == '&' || *cp == '|' || *cp == ')') {
1288 	    next_cmd = 1;
1289 	    if (copy) {
1290 		do {
1291 		    *cp-- = '\0';
1292 		} while (*cp == ';' || *cp == '&' || *cp == '|' ||
1293 			 *cp == ')' || *cp == '}') ;
1294 	    } else {
1295 		/*
1296 		 * XXX this should not happen.
1297 		 */
1298 		fprintf(stderr, "WARNING: raw arg ends in shell meta '%s'\n",
1299 			av[i]);
1300 	    }
1301 	} else
1302 	    next_cmd = 0;
1303 
1304 	cp = av[i];
1305 	if (*cp == ';' || *cp == '&' || *cp == '|')
1306 	    is_cmd = 1;
1307 
1308 #ifdef check_cwd_debug
1309 	fprintf(stderr, "av[%d] == %s '%s'",
1310 		i, (is_cmd) ? "cmd" : "arg", av[i]);
1311 #endif
1312 	if (is_cmd != 0) {
1313 	    if (*cp == '(' || *cp == '{' ||
1314 		*cp == ';' || *cp == '&' || *cp == '|') {
1315 		do {
1316 		    ++cp;
1317 		} while (*cp == '(' || *cp == '{' ||
1318 			 *cp == ';' || *cp == '&' || *cp == '|');
1319 		if (*cp == '\0') {
1320 		    next_cmd = 1;
1321 		    continue;
1322 		}
1323 	    }
1324 	    if (strcmp(cp, "cd") == 0 || strcmp(cp, "chdir") == 0) {
1325 #ifdef check_cwd_debug
1326 		fprintf(stderr, " == cd, done.\n");
1327 #endif
1328 		return NULL;
1329 	    }
1330 	    for (mp = make; *mp != NULL; ++mp) {
1331 		n = strlen(*mp);
1332 		if (strcmp(cp, *mp) == 0) {
1333 #ifdef check_cwd_debug
1334 		    fprintf(stderr, " %s == '%s', chdir(%s)\n",
1335 			    cp, *mp, cur_dir);
1336 #endif
1337 		    return cur_dir;
1338 		}
1339 	    }
1340 	}
1341 #ifdef check_cwd_debug
1342 	fprintf(stderr, "\n");
1343 #endif
1344     }
1345     return NULL;
1346 }
1347 
1348 char *
1349 Check_Cwd_Cmd(const char *cmd)
1350 {
1351     char *cp, *bp;
1352     char **av;
1353     int ac;
1354 
1355     if (Check_Cwd_Off)
1356 	return NULL;
1357 
1358     if (cmd) {
1359 	av = brk_string(cmd, &ac, TRUE, &bp);
1360 #ifdef check_cwd_debug
1361 	fprintf(stderr, "splitting: '%s' -> %d words\n",
1362 		cmd, ac);
1363 #endif
1364     } else {
1365 	ac = 0;
1366 	av = NULL;
1367 	bp = NULL;
1368     }
1369     cp = Check_Cwd_av(ac, av, 1);
1370     if (bp)
1371 	free(bp);
1372     if (av)
1373 	free(av);
1374     return cp;
1375 }
1376 
1377 void
1378 Check_Cwd(const char **argv)
1379 {
1380     char *cp;
1381     int ac;
1382 
1383     if (Check_Cwd_Off)
1384 	return;
1385 
1386     for (ac = 0; argv[ac] != NULL; ++ac)
1387 	/* NOTHING */;
1388     if (ac == 3 && *argv[1] == '-') {
1389 	cp =  Check_Cwd_Cmd(argv[2]);
1390     } else {
1391 	cp = Check_Cwd_av(ac, UNCONST(argv), 0);
1392     }
1393     if (cp) {
1394 	chdir(cp);
1395     }
1396 }
1397 
1398 /*-
1399  * Cmd_Exec --
1400  *	Execute the command in cmd, and return the output of that command
1401  *	in a string.
1402  *
1403  * Results:
1404  *	A string containing the output of the command, or the empty string
1405  *	If errnum is not NULL, it contains the reason for the command failure
1406  *
1407  * Side Effects:
1408  *	The string must be freed by the caller.
1409  */
1410 char *
1411 Cmd_Exec(const char *cmd, const char **errnum)
1412 {
1413     const char	*args[4];   	/* Args for invoking the shell */
1414     int 	fds[2];	    	/* Pipe streams */
1415     int 	cpid;	    	/* Child PID */
1416     int 	pid;	    	/* PID from wait() */
1417     char	*res;		/* result */
1418     int		status;		/* command exit status */
1419     Buffer	buf;		/* buffer to store the result */
1420     char	*cp;
1421     int		cc;
1422 
1423 
1424     *errnum = NULL;
1425 
1426     if (!shellName)
1427 	Shell_Init();
1428     /*
1429      * Set up arguments for shell
1430      */
1431     args[0] = shellName;
1432     args[1] = "-c";
1433     args[2] = cmd;
1434     args[3] = NULL;
1435 
1436     /*
1437      * Open a pipe for fetching its output
1438      */
1439     if (pipe(fds) == -1) {
1440 	*errnum = "Couldn't create pipe for \"%s\"";
1441 	goto bad;
1442     }
1443 
1444     /*
1445      * Fork
1446      */
1447     switch (cpid = vfork()) {
1448     case 0:
1449 	/*
1450 	 * Close input side of pipe
1451 	 */
1452 	(void)close(fds[0]);
1453 
1454 	/*
1455 	 * Duplicate the output stream to the shell's output, then
1456 	 * shut the extra thing down. Note we don't fetch the error
1457 	 * stream...why not? Why?
1458 	 */
1459 	(void)dup2(fds[1], 1);
1460 	(void)close(fds[1]);
1461 
1462 	Var_ExportVars();
1463 
1464 	(void)execv(shellPath, UNCONST(args));
1465 	_exit(1);
1466 	/*NOTREACHED*/
1467 
1468     case -1:
1469 	*errnum = "Couldn't exec \"%s\"";
1470 	goto bad;
1471 
1472     default:
1473 	/*
1474 	 * No need for the writing half
1475 	 */
1476 	(void)close(fds[1]);
1477 
1478 	buf = Buf_Init(0);
1479 
1480 	do {
1481 	    char   result[BUFSIZ];
1482 	    cc = read(fds[0], result, sizeof(result));
1483 	    if (cc > 0)
1484 		Buf_AddBytes(buf, cc, (Byte *)result);
1485 	}
1486 	while (cc > 0 || (cc == -1 && errno == EINTR));
1487 
1488 	/*
1489 	 * Close the input side of the pipe.
1490 	 */
1491 	(void)close(fds[0]);
1492 
1493 	/*
1494 	 * Wait for the process to exit.
1495 	 */
1496 	while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0))
1497 	    continue;
1498 
1499 	res = (char *)Buf_GetAll(buf, &cc);
1500 	Buf_Destroy(buf, FALSE);
1501 
1502 	if (cc == 0)
1503 	    *errnum = "Couldn't read shell's output for \"%s\"";
1504 
1505 	if (status)
1506 	    *errnum = "\"%s\" returned non-zero status";
1507 
1508 	/*
1509 	 * Null-terminate the result, convert newlines to spaces and
1510 	 * install it in the variable.
1511 	 */
1512 	res[cc] = '\0';
1513 	cp = &res[cc];
1514 
1515 	if (cc > 0 && *--cp == '\n') {
1516 	    /*
1517 	     * A final newline is just stripped
1518 	     */
1519 	    *cp-- = '\0';
1520 	}
1521 	while (cp >= res) {
1522 	    if (*cp == '\n') {
1523 		*cp = ' ';
1524 	    }
1525 	    cp--;
1526 	}
1527 	break;
1528     }
1529     return res;
1530 bad:
1531     res = emalloc(1);
1532     *res = '\0';
1533     return res;
1534 }
1535 
1536 /*-
1537  * Error --
1538  *	Print an error message given its format.
1539  *
1540  * Results:
1541  *	None.
1542  *
1543  * Side Effects:
1544  *	The message is printed.
1545  */
1546 /* VARARGS */
1547 void
1548 Error(const char *fmt, ...)
1549 {
1550 	va_list ap;
1551 
1552 	va_start(ap, fmt);
1553 	fprintf(stderr, "%s: ", progname);
1554 	(void)vfprintf(stderr, fmt, ap);
1555 	va_end(ap);
1556 	(void)fprintf(stderr, "\n");
1557 	(void)fflush(stderr);
1558 }
1559 
1560 /*-
1561  * Fatal --
1562  *	Produce a Fatal error message. If jobs are running, waits for them
1563  *	to finish.
1564  *
1565  * Results:
1566  *	None
1567  *
1568  * Side Effects:
1569  *	The program exits
1570  */
1571 /* VARARGS */
1572 void
1573 Fatal(const char *fmt, ...)
1574 {
1575 	va_list ap;
1576 
1577 	va_start(ap, fmt);
1578 	if (jobsRunning)
1579 		Job_Wait();
1580 
1581 	(void)vfprintf(stderr, fmt, ap);
1582 	va_end(ap);
1583 	(void)fprintf(stderr, "\n");
1584 	(void)fflush(stderr);
1585 
1586 	PrintOnError(NULL);
1587 
1588 	if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1589 		Targ_PrintGraph(2);
1590 	Trace_Log(MAKEERROR, 0);
1591 	exit(2);		/* Not 1 so -q can distinguish error */
1592 }
1593 
1594 /*
1595  * Punt --
1596  *	Major exception once jobs are being created. Kills all jobs, prints
1597  *	a message and exits.
1598  *
1599  * Results:
1600  *	None
1601  *
1602  * Side Effects:
1603  *	All children are killed indiscriminately and the program Lib_Exits
1604  */
1605 /* VARARGS */
1606 void
1607 Punt(const char *fmt, ...)
1608 {
1609 	va_list ap;
1610 
1611 	va_start(ap, fmt);
1612 	(void)fprintf(stderr, "%s: ", progname);
1613 	(void)vfprintf(stderr, fmt, ap);
1614 	va_end(ap);
1615 	(void)fprintf(stderr, "\n");
1616 	(void)fflush(stderr);
1617 
1618 	PrintOnError(NULL);
1619 
1620 	DieHorribly();
1621 }
1622 
1623 /*-
1624  * DieHorribly --
1625  *	Exit without giving a message.
1626  *
1627  * Results:
1628  *	None
1629  *
1630  * Side Effects:
1631  *	A big one...
1632  */
1633 void
1634 DieHorribly(void)
1635 {
1636 	if (jobsRunning)
1637 		Job_AbortAll();
1638 	if (DEBUG(GRAPH2))
1639 		Targ_PrintGraph(2);
1640 	Trace_Log(MAKEERROR, 0);
1641 	exit(2);		/* Not 1, so -q can distinguish error */
1642 }
1643 
1644 /*
1645  * Finish --
1646  *	Called when aborting due to errors in child shell to signal
1647  *	abnormal exit.
1648  *
1649  * Results:
1650  *	None
1651  *
1652  * Side Effects:
1653  *	The program exits
1654  */
1655 void
1656 Finish(int errors)
1657 	           	/* number of errors encountered in Make_Make */
1658 {
1659 	Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1660 }
1661 
1662 #ifndef HAVE_EMALLOC
1663 /*
1664  * emalloc --
1665  *	malloc, but die on error.
1666  */
1667 void *
1668 emalloc(size_t len)
1669 {
1670 	void *p;
1671 
1672 	if ((p = malloc(len)) == NULL)
1673 		enomem();
1674 	return(p);
1675 }
1676 
1677 /*
1678  * estrdup --
1679  *	strdup, but die on error.
1680  */
1681 char *
1682 estrdup(const char *str)
1683 {
1684 	char *p;
1685 
1686 	if ((p = strdup(str)) == NULL)
1687 		enomem();
1688 	return(p);
1689 }
1690 
1691 /*
1692  * estrndup --
1693  *	strndup, but die on error.
1694  */
1695 char *
1696 estrndup(const char *str, size_t len)
1697 {
1698 	char *p;
1699 
1700 	if ((p = strndup(str, len)) == NULL)
1701 		enomem();
1702 	return(p);
1703 }
1704 
1705 /*
1706  * erealloc --
1707  *	realloc, but die on error.
1708  */
1709 void *
1710 erealloc(void *ptr, size_t size)
1711 {
1712 	if ((ptr = realloc(ptr, size)) == NULL)
1713 		enomem();
1714 	return(ptr);
1715 }
1716 
1717 /*
1718  * enomem --
1719  *	die when out of memory.
1720  */
1721 void
1722 enomem(void)
1723 {
1724 	(void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
1725 	exit(2);
1726 }
1727 #endif
1728 
1729 /*
1730  * enunlink --
1731  *	Remove a file carefully, avoiding directories.
1732  */
1733 int
1734 eunlink(const char *file)
1735 {
1736 	struct stat st;
1737 
1738 	if (lstat(file, &st) == -1)
1739 		return -1;
1740 
1741 	if (S_ISDIR(st.st_mode)) {
1742 		errno = EISDIR;
1743 		return -1;
1744 	}
1745 	return unlink(file);
1746 }
1747 
1748 /*
1749  * execError --
1750  *	Print why exec failed, avoiding stdio.
1751  */
1752 void
1753 execError(const char *af, const char *av)
1754 {
1755 #ifdef USE_IOVEC
1756 	int i = 0;
1757 	struct iovec iov[8];
1758 #define IOADD(s) \
1759 	(void)(iov[i].iov_base = UNCONST(s), \
1760 	    iov[i].iov_len = strlen(iov[i].iov_base), \
1761 	    i++)
1762 #else
1763 #define	IOADD(void)write(2, s, strlen(s))
1764 #endif
1765 
1766 	IOADD(progname);
1767 	IOADD(": ");
1768 	IOADD(af);
1769 	IOADD("(");
1770 	IOADD(av);
1771 	IOADD(") failed (");
1772 	IOADD(strerror(errno));
1773 	IOADD(")\n");
1774 
1775 #ifdef USE_IOVEC
1776 	(void)writev(2, iov, 8);
1777 #endif
1778 }
1779 
1780 /*
1781  * usage --
1782  *	exit with usage message
1783  */
1784 static void
1785 usage(void)
1786 {
1787 	(void)fprintf(stderr,
1788 "usage: %s [-BeikNnqrstWX] [-D variable] [-d flags] [-f makefile]\n\
1789             [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1790             [-V variable] [variable=value] [target ...]\n", progname);
1791 	exit(2);
1792 }
1793 
1794 
1795 int
1796 PrintAddr(ClientData a, ClientData b)
1797 {
1798     printf("%lx ", (unsigned long) a);
1799     return b ? 0 : 0;
1800 }
1801 
1802 
1803 
1804 void
1805 PrintOnError(const char *s)
1806 {
1807     char tmp[64];
1808     char *cp;
1809 
1810     if (s)
1811 	    printf("%s", s);
1812 
1813     printf("\n%s: stopped in %s\n", progname, curdir);
1814     strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1815 	    sizeof(tmp) - 1);
1816     cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1817     if (cp) {
1818 	    if (*cp)
1819 		    printf("%s", cp);
1820 	    free(cp);
1821     }
1822 }
1823 
1824 void
1825 Main_ExportMAKEFLAGS(Boolean first)
1826 {
1827     static int once = 1;
1828     char tmp[64];
1829     char *s;
1830 
1831     if (once != first)
1832 	return;
1833     once = 0;
1834 
1835     strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1836 	    sizeof(tmp));
1837     s = Var_Subst(NULL, tmp, VAR_CMD, 0);
1838     if (s && *s) {
1839 #ifdef POSIX
1840 	setenv("MAKEFLAGS", s, 1);
1841 #else
1842 	setenv("MAKE", s, 1);
1843 #endif
1844     }
1845 }
1846