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