main.c revision 1.321 1 /* $NetBSD: main.c,v 1.321 2020/08/29 07:05:12 rillig 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.321 2020/08/29 07:05:12 rillig 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.321 2020/08/29 07:05:12 rillig 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 optional arguments
103 * for it.
104 *
105 * Fatal Print an error message and exit. Also takes
106 * a format string and arguments for it.
107 *
108 * Punt Aborts all jobs and exits with a message. Also
109 * takes a format string and arguments for it.
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/stat.h>
121 #ifdef MAKE_NATIVE
122 #include <sys/sysctl.h>
123 #endif
124 #include <sys/utsname.h>
125 #include <sys/wait.h>
126
127 #include <ctype.h>
128 #include <errno.h>
129 #include <signal.h>
130 #include <stdarg.h>
131 #include <stdio.h>
132 #include <stdlib.h>
133 #include <time.h>
134
135 #include "make.h"
136 #include "hash.h"
137 #include "dir.h"
138 #include "job.h"
139 #include "pathnames.h"
140 #include "trace.h"
141
142 #ifdef USE_IOVEC
143 #include <sys/uio.h>
144 #endif
145
146 #ifndef DEFMAXLOCAL
147 #define DEFMAXLOCAL DEFMAXJOBS
148 #endif /* DEFMAXLOCAL */
149
150 Lst create; /* Targets to be made */
151 time_t now; /* Time at start of make */
152 GNode *DEFAULT; /* .DEFAULT node */
153 Boolean allPrecious; /* .PRECIOUS given on line by itself */
154 Boolean deleteOnError; /* .DELETE_ON_ERROR: set */
155
156 static Boolean noBuiltins; /* -r flag */
157 static Lst makefiles; /* ordered list of makefiles to read */
158 static int printVars; /* -[vV] argument */
159 #define COMPAT_VARS 1
160 #define EXPAND_VARS 2
161 static Lst variables; /* list of variables to print */
162 int maxJobs; /* -j argument */
163 static int maxJobTokens; /* -j argument */
164 Boolean compatMake; /* -B argument */
165 int debug; /* -d argument */
166 Boolean debugVflag; /* -dV */
167 Boolean noExecute; /* -n flag */
168 Boolean noRecursiveExecute; /* -N flag */
169 Boolean keepgoing; /* -k flag */
170 Boolean queryFlag; /* -q flag */
171 Boolean touchFlag; /* -t flag */
172 Boolean enterFlag; /* -w flag */
173 Boolean enterFlagObj; /* -w and objdir != srcdir */
174 Boolean ignoreErrors; /* -i flag */
175 Boolean beSilent; /* -s flag */
176 Boolean oldVars; /* variable substitution style */
177 Boolean checkEnvFirst; /* -e flag */
178 Boolean parseWarnFatal; /* -W flag */
179 static int jp_0 = -1, jp_1 = -1; /* ends of parent job pipe */
180 Boolean varNoExportEnv; /* -X flag */
181 Boolean doing_depend; /* Set while reading .depend */
182 static Boolean jobsRunning; /* TRUE if the jobs might be running */
183 static const char * tracefile;
184 static void MainParseArgs(int, char **);
185 static int ReadMakefile(const void *, const void *);
186 static void usage(void) MAKE_ATTR_DEAD;
187 static void purge_cached_realpaths(void);
188
189 static Boolean ignorePWD; /* if we use -C, PWD is meaningless */
190 static char objdir[MAXPATHLEN + 1]; /* where we chdir'ed to */
191 char curdir[MAXPATHLEN + 1]; /* Startup directory */
192 char *progname; /* the program name */
193 char *makeDependfile;
194 pid_t myPid;
195 int makelevel;
196
197 FILE *debug_file;
198
199 Boolean forceJobs = FALSE;
200
201 extern Lst parseIncPath;
202
203 /*
204 * For compatibility with the POSIX version of MAKEFLAGS that includes
205 * all the options with out -, convert flags to -f -l -a -g -s.
206 */
207 static char *
208 explode(const char *flags)
209 {
210 size_t len;
211 char *nf, *st;
212 const char *f;
213
214 if (flags == NULL)
215 return NULL;
216
217 for (f = flags; *f; f++)
218 if (!isalpha((unsigned char)*f))
219 break;
220
221 if (*f)
222 return bmake_strdup(flags);
223
224 len = strlen(flags);
225 st = nf = bmake_malloc(len * 3 + 1);
226 while (*flags) {
227 *nf++ = '-';
228 *nf++ = *flags++;
229 *nf++ = ' ';
230 }
231 *nf = '\0';
232 return st;
233 }
234
235 static void
236 parse_debug_options(const char *argvalue)
237 {
238 const char *modules;
239 const char *mode;
240 char *fname;
241 int len;
242
243 for (modules = argvalue; *modules; ++modules) {
244 switch (*modules) {
245 case 'A':
246 debug = ~(0|DEBUG_LINT);
247 break;
248 case 'a':
249 debug |= DEBUG_ARCH;
250 break;
251 case 'C':
252 debug |= DEBUG_CWD;
253 break;
254 case 'c':
255 debug |= DEBUG_COND;
256 break;
257 case 'd':
258 debug |= DEBUG_DIR;
259 break;
260 case 'e':
261 debug |= DEBUG_ERROR;
262 break;
263 case 'f':
264 debug |= DEBUG_FOR;
265 break;
266 case 'g':
267 if (modules[1] == '1') {
268 debug |= DEBUG_GRAPH1;
269 ++modules;
270 }
271 else if (modules[1] == '2') {
272 debug |= DEBUG_GRAPH2;
273 ++modules;
274 }
275 else if (modules[1] == '3') {
276 debug |= DEBUG_GRAPH3;
277 ++modules;
278 }
279 break;
280 case 'h':
281 debug |= DEBUG_HASH;
282 break;
283 case 'j':
284 debug |= DEBUG_JOB;
285 break;
286 case 'L':
287 debug |= DEBUG_LINT;
288 break;
289 case 'l':
290 debug |= DEBUG_LOUD;
291 break;
292 case 'M':
293 debug |= DEBUG_META;
294 break;
295 case 'm':
296 debug |= DEBUG_MAKE;
297 break;
298 case 'n':
299 debug |= DEBUG_SCRIPT;
300 break;
301 case 'p':
302 debug |= DEBUG_PARSE;
303 break;
304 case 's':
305 debug |= DEBUG_SUFF;
306 break;
307 case 't':
308 debug |= DEBUG_TARG;
309 break;
310 case 'V':
311 debugVflag = TRUE;
312 break;
313 case 'v':
314 debug |= DEBUG_VAR;
315 break;
316 case 'x':
317 debug |= DEBUG_SHELL;
318 break;
319 case 'F':
320 if (debug_file != stdout && debug_file != stderr)
321 fclose(debug_file);
322 if (*++modules == '+') {
323 modules++;
324 mode = "a";
325 } else
326 mode = "w";
327 if (strcmp(modules, "stdout") == 0) {
328 debug_file = stdout;
329 goto debug_setbuf;
330 }
331 if (strcmp(modules, "stderr") == 0) {
332 debug_file = stderr;
333 goto debug_setbuf;
334 }
335 len = strlen(modules);
336 fname = bmake_malloc(len + 20);
337 memcpy(fname, modules, len + 1);
338 /* Let the filename be modified by the pid */
339 if (strcmp(fname + len - 3, ".%d") == 0)
340 snprintf(fname + len - 2, 20, "%d", getpid());
341 debug_file = fopen(fname, mode);
342 if (!debug_file) {
343 fprintf(stderr, "Cannot open debug file %s\n",
344 fname);
345 usage();
346 }
347 free(fname);
348 goto debug_setbuf;
349 default:
350 (void)fprintf(stderr,
351 "%s: illegal argument to d option -- %c\n",
352 progname, *modules);
353 usage();
354 }
355 }
356 debug_setbuf:
357 /*
358 * Make the debug_file unbuffered, and make
359 * stdout line buffered (unless debugfile == stdout).
360 */
361 setvbuf(debug_file, NULL, _IONBF, 0);
362 if (debug_file != stdout) {
363 setvbuf(stdout, NULL, _IOLBF, 0);
364 }
365 }
366
367 /*
368 * does path contain any relative components
369 */
370 static Boolean
371 is_relpath(const char *path)
372 {
373 const char *cp;
374
375 if (path[0] != '/')
376 return TRUE;
377 cp = path;
378 while ((cp = strstr(cp, "/.")) != NULL) {
379 cp += 2;
380 if (cp[0] == '/' || cp[0] == '\0')
381 return TRUE;
382 else if (cp[0] == '.') {
383 if (cp[1] == '/' || cp[1] == '\0')
384 return TRUE;
385 }
386 }
387 return FALSE;
388 }
389
390 /*-
391 * MainParseArgs --
392 * Parse a given argument vector. Called from main() and from
393 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
394 *
395 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
396 *
397 * Results:
398 * None
399 *
400 * Side Effects:
401 * Various global and local flags will be set depending on the flags
402 * given
403 */
404 static void
405 MainParseArgs(int argc, char **argv)
406 {
407 char *p;
408 int c = '?';
409 int arginc;
410 char *argvalue;
411 const char *getopt_def;
412 struct stat sa, sb;
413 char *optscan;
414 Boolean inOption, dashDash = FALSE;
415 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
416
417 #define OPTFLAGS "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrstv:w"
418 /* Can't actually use getopt(3) because rescanning is not portable */
419
420 getopt_def = OPTFLAGS;
421 rearg:
422 inOption = FALSE;
423 optscan = NULL;
424 while(argc > 1) {
425 char *getopt_spec;
426 if(!inOption)
427 optscan = argv[1];
428 c = *optscan++;
429 arginc = 0;
430 if(inOption) {
431 if(c == '\0') {
432 ++argv;
433 --argc;
434 inOption = FALSE;
435 continue;
436 }
437 } else {
438 if (c != '-' || dashDash)
439 break;
440 inOption = TRUE;
441 c = *optscan++;
442 }
443 /* '-' found at some earlier point */
444 getopt_spec = strchr(getopt_def, c);
445 if(c != '\0' && getopt_spec != NULL && getopt_spec[1] == ':') {
446 /* -<something> found, and <something> should have an arg */
447 inOption = FALSE;
448 arginc = 1;
449 argvalue = optscan;
450 if(*argvalue == '\0') {
451 if (argc < 3)
452 goto noarg;
453 argvalue = argv[2];
454 arginc = 2;
455 }
456 } else {
457 argvalue = NULL;
458 }
459 switch(c) {
460 case '\0':
461 arginc = 1;
462 inOption = FALSE;
463 break;
464 case 'B':
465 compatMake = TRUE;
466 Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
467 Var_Set(MAKE_MODE, "compat", VAR_GLOBAL);
468 break;
469 case 'C':
470 if (chdir(argvalue) == -1) {
471 (void)fprintf(stderr,
472 "%s: chdir %s: %s\n",
473 progname, argvalue,
474 strerror(errno));
475 exit(1);
476 }
477 if (getcwd(curdir, MAXPATHLEN) == NULL) {
478 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
479 exit(2);
480 }
481 if (!is_relpath(argvalue) &&
482 stat(argvalue, &sa) != -1 &&
483 stat(curdir, &sb) != -1 &&
484 sa.st_ino == sb.st_ino &&
485 sa.st_dev == sb.st_dev)
486 strncpy(curdir, argvalue, MAXPATHLEN);
487 ignorePWD = TRUE;
488 break;
489 case 'D':
490 if (argvalue == NULL || argvalue[0] == 0) goto noarg;
491 Var_Set(argvalue, "1", VAR_GLOBAL);
492 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
493 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
494 break;
495 case 'I':
496 if (argvalue == NULL) goto noarg;
497 Parse_AddIncludeDir(argvalue);
498 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
499 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
500 break;
501 case 'J':
502 if (argvalue == NULL) goto noarg;
503 if (sscanf(argvalue, "%d,%d", &jp_0, &jp_1) != 2) {
504 (void)fprintf(stderr,
505 "%s: internal error -- J option malformed (%s)\n",
506 progname, argvalue);
507 usage();
508 }
509 if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
510 (fcntl(jp_1, F_GETFD, 0) < 0)) {
511 #if 0
512 (void)fprintf(stderr,
513 "%s: ###### warning -- J descriptors were closed!\n",
514 progname);
515 exit(2);
516 #endif
517 jp_0 = -1;
518 jp_1 = -1;
519 compatMake = TRUE;
520 } else {
521 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
522 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
523 }
524 break;
525 case 'N':
526 noExecute = TRUE;
527 noRecursiveExecute = TRUE;
528 Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
529 break;
530 case 'S':
531 keepgoing = FALSE;
532 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
533 break;
534 case 'T':
535 if (argvalue == NULL) goto noarg;
536 tracefile = bmake_strdup(argvalue);
537 Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
538 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
539 break;
540 case 'V':
541 case 'v':
542 if (argvalue == NULL) goto noarg;
543 printVars = c == 'v' ? EXPAND_VARS : COMPAT_VARS;
544 Lst_Append(variables, argvalue);
545 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
546 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
547 break;
548 case 'W':
549 parseWarnFatal = TRUE;
550 break;
551 case 'X':
552 varNoExportEnv = TRUE;
553 Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
554 break;
555 case 'd':
556 if (argvalue == NULL) goto noarg;
557 /* If '-d-opts' don't pass to children */
558 if (argvalue[0] == '-')
559 argvalue++;
560 else {
561 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
562 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
563 }
564 parse_debug_options(argvalue);
565 break;
566 case 'e':
567 checkEnvFirst = TRUE;
568 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
569 break;
570 case 'f':
571 if (argvalue == NULL) goto noarg;
572 Lst_Append(makefiles, argvalue);
573 break;
574 case 'i':
575 ignoreErrors = TRUE;
576 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
577 break;
578 case 'j':
579 if (argvalue == NULL) goto noarg;
580 forceJobs = TRUE;
581 maxJobs = strtol(argvalue, &p, 0);
582 if (*p != '\0' || maxJobs < 1) {
583 (void)fprintf(stderr, "%s: illegal argument to -j -- must be positive integer!\n",
584 progname);
585 exit(1);
586 }
587 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
588 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
589 Var_Set(".MAKE.JOBS", argvalue, VAR_GLOBAL);
590 maxJobTokens = maxJobs;
591 break;
592 case 'k':
593 keepgoing = TRUE;
594 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
595 break;
596 case 'm':
597 if (argvalue == NULL) goto noarg;
598 /* look for magic parent directory search string */
599 if (strncmp(".../", argvalue, 4) == 0) {
600 if (!Dir_FindHereOrAbove(curdir, argvalue+4,
601 found_path, sizeof(found_path)))
602 break; /* nothing doing */
603 (void)Dir_AddDir(sysIncPath, found_path);
604 } else {
605 (void)Dir_AddDir(sysIncPath, argvalue);
606 }
607 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
608 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
609 break;
610 case 'n':
611 noExecute = TRUE;
612 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
613 break;
614 case 'q':
615 queryFlag = TRUE;
616 /* Kind of nonsensical, wot? */
617 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
618 break;
619 case 'r':
620 noBuiltins = TRUE;
621 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
622 break;
623 case 's':
624 beSilent = TRUE;
625 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
626 break;
627 case 't':
628 touchFlag = TRUE;
629 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
630 break;
631 case 'w':
632 enterFlag = TRUE;
633 Var_Append(MAKEFLAGS, "-w", VAR_GLOBAL);
634 break;
635 case '-':
636 dashDash = TRUE;
637 break;
638 default:
639 case '?':
640 usage();
641 }
642 argv += arginc;
643 argc -= arginc;
644 }
645
646 oldVars = TRUE;
647
648 /*
649 * See if the rest of the arguments are variable assignments and
650 * perform them if so. Else take them to be targets and stuff them
651 * on the end of the "create" list.
652 */
653 for (; argc > 1; ++argv, --argc)
654 if (Parse_IsVar(argv[1])) {
655 Parse_DoVar(argv[1], VAR_CMD);
656 } else {
657 if (!*argv[1])
658 Punt("illegal (null) argument.");
659 if (*argv[1] == '-' && !dashDash)
660 goto rearg;
661 Lst_Append(create, bmake_strdup(argv[1]));
662 }
663
664 return;
665 noarg:
666 (void)fprintf(stderr, "%s: option requires an argument -- %c\n",
667 progname, c);
668 usage();
669 }
670
671 /*-
672 * Main_ParseArgLine --
673 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
674 * is encountered and by main() when reading the .MAKEFLAGS envariable.
675 * Takes a line of arguments and breaks it into its
676 * component words and passes those words and the number of them to the
677 * MainParseArgs function.
678 * The line should have all its leading whitespace removed.
679 *
680 * Input:
681 * line Line to fracture
682 *
683 * Results:
684 * None
685 *
686 * Side Effects:
687 * Only those that come from the various arguments.
688 */
689 void
690 Main_ParseArgLine(const char *line)
691 {
692 char **argv; /* Manufactured argument vector */
693 size_t argc; /* Number of arguments in argv */
694 char *args; /* Space used by the args */
695 char *p1;
696 const char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
697 char *buf;
698
699 if (line == NULL)
700 return;
701 for (; *line == ' '; ++line)
702 continue;
703 if (!*line)
704 return;
705
706 buf = str_concat3(argv0, " ", line);
707 free(p1);
708
709 argv = brk_string(buf, TRUE, &argc, &args);
710 if (argv == NULL) {
711 Error("Unterminated quoted string [%s]", buf);
712 free(buf);
713 return;
714 }
715 free(buf);
716 MainParseArgs((int)argc, argv);
717
718 free(args);
719 free(argv);
720 }
721
722 Boolean
723 Main_SetObjdir(const char *fmt, ...)
724 {
725 struct stat sb;
726 char *path;
727 char buf[MAXPATHLEN + 1];
728 char buf2[MAXPATHLEN + 1];
729 Boolean rc = FALSE;
730 va_list ap;
731
732 va_start(ap, fmt);
733 vsnprintf(path = buf, MAXPATHLEN, fmt, ap);
734 va_end(ap);
735
736 if (path[0] != '/') {
737 snprintf(buf2, MAXPATHLEN, "%s/%s", curdir, path);
738 path = buf2;
739 }
740
741 /* look for the directory and try to chdir there */
742 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
743 if (chdir(path)) {
744 (void)fprintf(stderr, "make warning: %s: %s.\n",
745 path, strerror(errno));
746 } else {
747 snprintf(objdir, sizeof objdir, "%s", path);
748 Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
749 setenv("PWD", objdir, 1);
750 Dir_InitDot();
751 purge_cached_realpaths();
752 rc = TRUE;
753 if (enterFlag && strcmp(objdir, curdir) != 0)
754 enterFlagObj = TRUE;
755 }
756 }
757
758 return rc;
759 }
760
761 static Boolean
762 Main_SetVarObjdir(const char *var, const char *suffix)
763 {
764 char *path_freeIt;
765 const char *path = Var_Value(var, VAR_CMD, &path_freeIt);
766 const char *xpath;
767 char *xpath_freeIt;
768
769 if (path == NULL || path[0] == '\0') {
770 bmake_free(path_freeIt);
771 return FALSE;
772 }
773
774 /* expand variable substitutions */
775 xpath = path;
776 xpath_freeIt = NULL;
777 if (strchr(path, '$') != 0)
778 xpath = xpath_freeIt = Var_Subst(path, VAR_GLOBAL,
779 VARE_WANTRES);
780
781 (void)Main_SetObjdir("%s%s", xpath, suffix);
782
783 bmake_free(xpath_freeIt);
784 bmake_free(path_freeIt);
785 return TRUE;
786 }
787
788 /* Return 0 if reading the makefile failed, for Lst_Find. */
789 static int
790 ReadMakefileFailed(const void *p, const void *q)
791 {
792 return ReadMakefile(p, q) == 0;
793 }
794
795 int
796 str2Lst_Append(Lst lp, char *str, const char *sep)
797 {
798 char *cp;
799 int n;
800
801 if (!sep)
802 sep = " \t";
803
804 for (n = 0, cp = strtok(str, sep); cp; cp = strtok(NULL, sep)) {
805 Lst_Append(lp, cp);
806 n++;
807 }
808 return n;
809 }
810
811 #ifdef SIGINFO
812 /*ARGSUSED*/
813 static void
814 siginfo(int signo MAKE_ATTR_UNUSED)
815 {
816 char dir[MAXPATHLEN];
817 char str[2 * MAXPATHLEN];
818 int len;
819 if (getcwd(dir, sizeof(dir)) == NULL)
820 return;
821 len = snprintf(str, sizeof(str), "%s: Working in: %s\n", progname, dir);
822 if (len > 0)
823 (void)write(STDERR_FILENO, str, (size_t)len);
824 }
825 #endif
826
827 /*
828 * Allow makefiles some control over the mode we run in.
829 */
830 void
831 MakeMode(const char *mode)
832 {
833 char *mp = NULL;
834
835 if (!mode)
836 mode = mp = Var_Subst("${" MAKE_MODE ":tl}",
837 VAR_GLOBAL, VARE_WANTRES);
838
839 if (mode && *mode) {
840 if (strstr(mode, "compat")) {
841 compatMake = TRUE;
842 forceJobs = FALSE;
843 }
844 #if USE_META
845 if (strstr(mode, "meta"))
846 meta_mode_init(mode);
847 #endif
848 }
849
850 free(mp);
851 }
852
853 static void
854 doPrintVars(void)
855 {
856 LstNode ln;
857 Boolean expandVars;
858
859 if (printVars == EXPAND_VARS)
860 expandVars = TRUE;
861 else if (debugVflag)
862 expandVars = FALSE;
863 else
864 expandVars = getBoolean(".MAKE.EXPAND_VARIABLES", FALSE);
865
866 for (ln = Lst_First(variables); ln != NULL; ln = Lst_Succ(ln)) {
867 char *var = Lst_Datum(ln);
868 const char *value;
869 char *p1;
870
871 if (strchr(var, '$')) {
872 value = p1 = Var_Subst(var, VAR_GLOBAL, VARE_WANTRES);
873 } else if (expandVars) {
874 char tmp[128];
875 int len = snprintf(tmp, sizeof(tmp), "${%s}", var);
876
877 if (len >= (int)sizeof(tmp))
878 Fatal("%s: variable name too big: %s",
879 progname, var);
880 value = p1 = Var_Subst(tmp, VAR_GLOBAL, VARE_WANTRES);
881 } else {
882 value = Var_Value(var, VAR_GLOBAL, &p1);
883 }
884 printf("%s\n", value ? value : "");
885 bmake_free(p1);
886 }
887 }
888
889 static Boolean
890 runTargets(void)
891 {
892 Lst targs; /* target nodes to create -- passed to Make_Init */
893 Boolean outOfDate; /* FALSE if all targets up to date */
894
895 /*
896 * Have now read the entire graph and need to make a list of
897 * targets to create. If none was given on the command line,
898 * we consult the parsing module to find the main target(s)
899 * to create.
900 */
901 if (Lst_IsEmpty(create))
902 targs = Parse_MainName();
903 else
904 targs = Targ_FindList(create, TARG_CREATE);
905
906 if (!compatMake) {
907 /*
908 * Initialize job module before traversing the graph
909 * now that any .BEGIN and .END targets have been read.
910 * This is done only if the -q flag wasn't given
911 * (to prevent the .BEGIN from being executed should
912 * it exist).
913 */
914 if (!queryFlag) {
915 Job_Init();
916 jobsRunning = TRUE;
917 }
918
919 /* Traverse the graph, checking on all the targets */
920 outOfDate = Make_Run(targs);
921 } else {
922 /*
923 * Compat_Init will take care of creating all the
924 * targets as well as initializing the module.
925 */
926 Compat_Run(targs);
927 outOfDate = FALSE;
928 }
929 Lst_Free(targs);
930 return outOfDate;
931 }
932
933 /*-
934 * main --
935 * The main function, for obvious reasons. Initializes variables
936 * and a few modules, then parses the arguments give it in the
937 * environment and on the command line. Reads the system makefile
938 * followed by either Makefile, makefile or the file given by the
939 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
940 * flags it has received by then uses either the Make or the Compat
941 * module to create the initial list of targets.
942 *
943 * Results:
944 * If -q was given, exits -1 if anything was out-of-date. Else it exits
945 * 0.
946 *
947 * Side Effects:
948 * The program exits when done. Targets are created. etc. etc. etc.
949 */
950 int
951 main(int argc, char **argv)
952 {
953 Boolean outOfDate; /* FALSE if all targets up to date */
954 struct stat sb, sa;
955 char *p1, *path;
956 char mdpath[MAXPATHLEN];
957 const char *machine = getenv("MACHINE");
958 const char *machine_arch = getenv("MACHINE_ARCH");
959 char *syspath = getenv("MAKESYSPATH");
960 Lst sysMkPath; /* Path of sys.mk */
961 char *cp = NULL, *start;
962 /* avoid faults on read-only strings */
963 static char defsyspath[] = _PATH_DEFSYSPATH;
964 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
965 struct timeval rightnow; /* to initialize random seed */
966 struct utsname utsname;
967
968 /* default to writing debug to stderr */
969 debug_file = stderr;
970
971 #ifdef SIGINFO
972 (void)bmake_signal(SIGINFO, siginfo);
973 #endif
974 /*
975 * Set the seed to produce a different random sequence
976 * on each program execution.
977 */
978 gettimeofday(&rightnow, NULL);
979 srandom(rightnow.tv_sec + rightnow.tv_usec);
980
981 if ((progname = strrchr(argv[0], '/')) != NULL)
982 progname++;
983 else
984 progname = argv[0];
985 #if defined(MAKE_NATIVE) || (defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE))
986 /*
987 * get rid of resource limit on file descriptors
988 */
989 {
990 struct rlimit rl;
991 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
992 rl.rlim_cur != rl.rlim_max) {
993 rl.rlim_cur = rl.rlim_max;
994 (void)setrlimit(RLIMIT_NOFILE, &rl);
995 }
996 }
997 #endif
998
999 if (uname(&utsname) == -1) {
1000 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
1001 strerror(errno));
1002 exit(2);
1003 }
1004
1005 /*
1006 * Get the name of this type of MACHINE from utsname
1007 * so we can share an executable for similar machines.
1008 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
1009 *
1010 * Note that both MACHINE and MACHINE_ARCH are decided at
1011 * run-time.
1012 */
1013 if (!machine) {
1014 #ifdef MAKE_NATIVE
1015 machine = utsname.machine;
1016 #else
1017 #ifdef MAKE_MACHINE
1018 machine = MAKE_MACHINE;
1019 #else
1020 machine = "unknown";
1021 #endif
1022 #endif
1023 }
1024
1025 if (!machine_arch) {
1026 #ifdef MAKE_NATIVE
1027 static char machine_arch_buf[sizeof(utsname.machine)];
1028 const int mib[2] = { CTL_HW, HW_MACHINE_ARCH };
1029 size_t len = sizeof(machine_arch_buf);
1030
1031 if (sysctl(mib, __arraycount(mib), machine_arch_buf,
1032 &len, NULL, 0) < 0) {
1033 (void)fprintf(stderr, "%s: sysctl failed (%s).\n", progname,
1034 strerror(errno));
1035 exit(2);
1036 }
1037
1038 machine_arch = machine_arch_buf;
1039 #else
1040 #ifndef MACHINE_ARCH
1041 #ifdef MAKE_MACHINE_ARCH
1042 machine_arch = MAKE_MACHINE_ARCH;
1043 #else
1044 machine_arch = "unknown";
1045 #endif
1046 #else
1047 machine_arch = MACHINE_ARCH;
1048 #endif
1049 #endif
1050 }
1051
1052 myPid = getpid(); /* remember this for vFork() */
1053
1054 /*
1055 * Just in case MAKEOBJDIR wants us to do something tricky.
1056 */
1057 Var_Init(); /* Initialize the lists of variables for
1058 * parsing arguments */
1059 Var_Set(".MAKE.OS", utsname.sysname, VAR_GLOBAL);
1060 Var_Set("MACHINE", machine, VAR_GLOBAL);
1061 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
1062 #ifdef MAKE_VERSION
1063 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
1064 #endif
1065 Var_Set(".newline", "\n", VAR_GLOBAL); /* handy for :@ loops */
1066 /*
1067 * This is the traditional preference for makefiles.
1068 */
1069 #ifndef MAKEFILE_PREFERENCE_LIST
1070 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
1071 #endif
1072 Var_Set(MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST,
1073 VAR_GLOBAL);
1074 Var_Set(MAKE_DEPENDFILE, ".depend", VAR_GLOBAL);
1075
1076 create = Lst_Init();
1077 makefiles = Lst_Init();
1078 printVars = 0;
1079 debugVflag = FALSE;
1080 variables = Lst_Init();
1081 beSilent = FALSE; /* Print commands as executed */
1082 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
1083 noExecute = FALSE; /* Execute all commands */
1084 noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
1085 keepgoing = FALSE; /* Stop on error */
1086 allPrecious = FALSE; /* Remove targets when interrupted */
1087 deleteOnError = FALSE; /* Historical default behavior */
1088 queryFlag = FALSE; /* This is not just a check-run */
1089 noBuiltins = FALSE; /* Read the built-in rules */
1090 touchFlag = FALSE; /* Actually update targets */
1091 debug = 0; /* No debug verbosity, please. */
1092 jobsRunning = FALSE;
1093
1094 maxJobs = DEFMAXLOCAL; /* Set default local max concurrency */
1095 maxJobTokens = maxJobs;
1096 compatMake = FALSE; /* No compat mode */
1097 ignorePWD = FALSE;
1098
1099 /*
1100 * Initialize the parsing, directory and variable modules to prepare
1101 * for the reading of inclusion paths and variable settings on the
1102 * command line
1103 */
1104
1105 /*
1106 * Initialize various variables.
1107 * MAKE also gets this name, for compatibility
1108 * .MAKEFLAGS gets set to the empty string just in case.
1109 * MFLAGS also gets initialized empty, for compatibility.
1110 */
1111 Parse_Init();
1112 if (argv[0][0] == '/' || strchr(argv[0], '/') == NULL) {
1113 /*
1114 * Leave alone if it is an absolute path, or if it does
1115 * not contain a '/' in which case we need to find it in
1116 * the path, like execvp(3) and the shells do.
1117 */
1118 p1 = argv[0];
1119 } else {
1120 /*
1121 * A relative path, canonicalize it.
1122 */
1123 p1 = cached_realpath(argv[0], mdpath);
1124 if (!p1 || *p1 != '/' || stat(p1, &sb) < 0) {
1125 p1 = argv[0]; /* realpath failed */
1126 }
1127 }
1128 Var_Set("MAKE", p1, VAR_GLOBAL);
1129 Var_Set(".MAKE", p1, VAR_GLOBAL);
1130 Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
1131 Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL);
1132 Var_Set("MFLAGS", "", VAR_GLOBAL);
1133 Var_Set(".ALLTARGETS", "", VAR_GLOBAL);
1134 /* some makefiles need to know this */
1135 Var_Set(MAKE_LEVEL ".ENV", MAKE_LEVEL_ENV, VAR_CMD);
1136
1137 /*
1138 * Set some other useful macros
1139 */
1140 {
1141 char tmp[64], *ep;
1142
1143 makelevel = ((ep = getenv(MAKE_LEVEL_ENV)) && *ep) ? atoi(ep) : 0;
1144 if (makelevel < 0)
1145 makelevel = 0;
1146 snprintf(tmp, sizeof(tmp), "%d", makelevel);
1147 Var_Set(MAKE_LEVEL, tmp, VAR_GLOBAL);
1148 snprintf(tmp, sizeof(tmp), "%u", myPid);
1149 Var_Set(".MAKE.PID", tmp, VAR_GLOBAL);
1150 snprintf(tmp, sizeof(tmp), "%u", getppid());
1151 Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL);
1152 }
1153 if (makelevel > 0) {
1154 char pn[1024];
1155 snprintf(pn, sizeof(pn), "%s[%d]", progname, makelevel);
1156 progname = bmake_strdup(pn);
1157 }
1158
1159 #ifdef USE_META
1160 meta_init();
1161 #endif
1162 Dir_Init();
1163
1164 /*
1165 * First snag any flags out of the MAKE environment variable.
1166 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
1167 * in a different format).
1168 */
1169 #ifdef POSIX
1170 p1 = explode(getenv("MAKEFLAGS"));
1171 Main_ParseArgLine(p1);
1172 free(p1);
1173 #else
1174 Main_ParseArgLine(getenv("MAKE"));
1175 #endif
1176
1177 /*
1178 * Find where we are (now).
1179 * We take care of PWD for the automounter below...
1180 */
1181 if (getcwd(curdir, MAXPATHLEN) == NULL) {
1182 (void)fprintf(stderr, "%s: getcwd: %s.\n",
1183 progname, strerror(errno));
1184 exit(2);
1185 }
1186
1187 MainParseArgs(argc, argv);
1188
1189 if (enterFlag)
1190 printf("%s: Entering directory `%s'\n", progname, curdir);
1191
1192 /*
1193 * Verify that cwd is sane.
1194 */
1195 if (stat(curdir, &sa) == -1) {
1196 (void)fprintf(stderr, "%s: %s: %s.\n",
1197 progname, curdir, strerror(errno));
1198 exit(2);
1199 }
1200
1201 /*
1202 * All this code is so that we know where we are when we start up
1203 * on a different machine with pmake.
1204 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
1205 * since the value of curdir can vary depending on how we got
1206 * here. Ie sitting at a shell prompt (shell that provides $PWD)
1207 * or via subdir.mk in which case its likely a shell which does
1208 * not provide it.
1209 * So, to stop it breaking this case only, we ignore PWD if
1210 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
1211 */
1212 #ifndef NO_PWD_OVERRIDE
1213 if (!ignorePWD) {
1214 char *pwd, *ptmp1 = NULL, *ptmp2 = NULL;
1215
1216 if ((pwd = getenv("PWD")) != NULL &&
1217 Var_Value("MAKEOBJDIRPREFIX", VAR_CMD, &ptmp1) == NULL) {
1218 const char *makeobjdir = Var_Value("MAKEOBJDIR",
1219 VAR_CMD, &ptmp2);
1220
1221 if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
1222 if (stat(pwd, &sb) == 0 &&
1223 sa.st_ino == sb.st_ino &&
1224 sa.st_dev == sb.st_dev)
1225 (void)strncpy(curdir, pwd, MAXPATHLEN);
1226 }
1227 }
1228 bmake_free(ptmp1);
1229 bmake_free(ptmp2);
1230 }
1231 #endif
1232 Var_Set(".CURDIR", curdir, VAR_GLOBAL);
1233
1234 /*
1235 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
1236 * MAKEOBJDIR is set in the environment, try only that value
1237 * and fall back to .CURDIR if it does not exist.
1238 *
1239 * Otherwise, try _PATH_OBJDIR.MACHINE-MACHINE_ARCH, _PATH_OBJDIR.MACHINE,
1240 * and * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
1241 * of these paths exist, just use .CURDIR.
1242 */
1243 Dir_InitDir(curdir);
1244 (void)Main_SetObjdir("%s", curdir);
1245
1246 if (!Main_SetVarObjdir("MAKEOBJDIRPREFIX", curdir) &&
1247 !Main_SetVarObjdir("MAKEOBJDIR", "") &&
1248 !Main_SetObjdir("%s.%s-%s", _PATH_OBJDIR, machine, machine_arch) &&
1249 !Main_SetObjdir("%s.%s", _PATH_OBJDIR, machine) &&
1250 !Main_SetObjdir("%s", _PATH_OBJDIR))
1251 (void)Main_SetObjdir("%s%s", _PATH_OBJDIRPREFIX, curdir);
1252
1253 /*
1254 * Initialize archive, target and suffix modules in preparation for
1255 * parsing the makefile(s)
1256 */
1257 Arch_Init();
1258 Targ_Init();
1259 Suff_Init();
1260 Trace_Init(tracefile);
1261
1262 DEFAULT = NULL;
1263 (void)time(&now);
1264
1265 Trace_Log(MAKESTART, NULL);
1266
1267 /*
1268 * Set up the .TARGETS variable to contain the list of targets to be
1269 * created. If none specified, make the variable empty -- the parser
1270 * will fill the thing in with the default or .MAIN target.
1271 */
1272 if (!Lst_IsEmpty(create)) {
1273 LstNode ln;
1274
1275 for (ln = Lst_First(create); ln != NULL; ln = Lst_Succ(ln)) {
1276 char *name = Lst_Datum(ln);
1277 Var_Append(".TARGETS", name, VAR_GLOBAL);
1278 }
1279 } else
1280 Var_Set(".TARGETS", "", VAR_GLOBAL);
1281
1282
1283 /*
1284 * If no user-supplied system path was given (through the -m option)
1285 * add the directories from the DEFSYSPATH (more than one may be given
1286 * as dir1:...:dirn) to the system include path.
1287 */
1288 if (syspath == NULL || *syspath == '\0')
1289 syspath = defsyspath;
1290 else
1291 syspath = bmake_strdup(syspath);
1292
1293 for (start = syspath; *start != '\0'; start = cp) {
1294 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1295 continue;
1296 if (*cp == ':') {
1297 *cp++ = '\0';
1298 }
1299 /* look for magic parent directory search string */
1300 if (strncmp(".../", start, 4) != 0) {
1301 (void)Dir_AddDir(defIncPath, start);
1302 } else {
1303 if (Dir_FindHereOrAbove(curdir, start+4,
1304 found_path, sizeof(found_path))) {
1305 (void)Dir_AddDir(defIncPath, found_path);
1306 }
1307 }
1308 }
1309 if (syspath != defsyspath)
1310 free(syspath);
1311
1312 /*
1313 * Read in the built-in rules first, followed by the specified
1314 * makefile, if it was (makefile != NULL), or the default
1315 * makefile and Makefile, in that order, if it wasn't.
1316 */
1317 if (!noBuiltins) {
1318 LstNode ln;
1319
1320 sysMkPath = Lst_Init();
1321 Dir_Expand(_PATH_DEFSYSMK,
1322 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
1323 sysMkPath);
1324 if (Lst_IsEmpty(sysMkPath))
1325 Fatal("%s: no system rules (%s).", progname,
1326 _PATH_DEFSYSMK);
1327 ln = Lst_Find(sysMkPath, ReadMakefile, NULL);
1328 if (ln == NULL)
1329 Fatal("%s: cannot open %s.", progname,
1330 (char *)Lst_Datum(ln));
1331 }
1332
1333 if (!Lst_IsEmpty(makefiles)) {
1334 LstNode ln;
1335
1336 ln = Lst_Find(makefiles, ReadMakefileFailed, NULL);
1337 if (ln != NULL)
1338 Fatal("%s: cannot open %s.", progname,
1339 (char *)Lst_Datum(ln));
1340 } else {
1341 p1 = Var_Subst("${" MAKEFILE_PREFERENCE "}",
1342 VAR_CMD, VARE_WANTRES);
1343 if (p1) {
1344 (void)str2Lst_Append(makefiles, p1, NULL);
1345 (void)Lst_Find(makefiles, ReadMakefile, NULL);
1346 free(p1);
1347 }
1348 }
1349
1350 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1351 if (!noBuiltins || !printVars) {
1352 makeDependfile = Var_Subst("${.MAKE.DEPENDFILE:T}",
1353 VAR_CMD, VARE_WANTRES);
1354 doing_depend = TRUE;
1355 (void)ReadMakefile(makeDependfile, NULL);
1356 doing_depend = FALSE;
1357 }
1358
1359 if (enterFlagObj)
1360 printf("%s: Entering directory `%s'\n", progname, objdir);
1361
1362 MakeMode(NULL);
1363
1364 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
1365 bmake_free(p1);
1366
1367 if (!forceJobs && !compatMake &&
1368 Var_Exists(".MAKE.JOBS", VAR_GLOBAL)) {
1369 char *value;
1370 int n;
1371
1372 value = Var_Subst("${.MAKE.JOBS}", VAR_GLOBAL, VARE_WANTRES);
1373 n = strtol(value, NULL, 0);
1374 if (n < 1) {
1375 (void)fprintf(stderr, "%s: illegal value for .MAKE.JOBS -- must be positive integer!\n",
1376 progname);
1377 exit(1);
1378 }
1379 if (n != maxJobs) {
1380 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
1381 Var_Append(MAKEFLAGS, value, VAR_GLOBAL);
1382 }
1383 maxJobs = n;
1384 maxJobTokens = maxJobs;
1385 forceJobs = TRUE;
1386 free(value);
1387 }
1388
1389 /*
1390 * Be compatible if user did not specify -j and did not explicitly
1391 * turned compatibility on
1392 */
1393 if (!compatMake && !forceJobs) {
1394 compatMake = TRUE;
1395 }
1396
1397 if (!compatMake)
1398 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1399 if (DEBUG(JOB))
1400 fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1401 jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
1402
1403 if (!printVars)
1404 Main_ExportMAKEFLAGS(TRUE); /* initial export */
1405
1406
1407 /*
1408 * For compatibility, look at the directories in the VPATH variable
1409 * and add them to the search path, if the variable is defined. The
1410 * variable's value is in the same format as the PATH envariable, i.e.
1411 * <directory>:<directory>:<directory>...
1412 */
1413 if (Var_Exists("VPATH", VAR_CMD)) {
1414 char *vpath, savec;
1415 /*
1416 * GCC stores string constants in read-only memory, but
1417 * Var_Subst will want to write this thing, so store it
1418 * in an array
1419 */
1420 static char VPATH[] = "${VPATH}";
1421
1422 vpath = Var_Subst(VPATH, VAR_CMD, VARE_WANTRES);
1423 path = vpath;
1424 do {
1425 /* skip to end of directory */
1426 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1427 continue;
1428 /* Save terminator character so know when to stop */
1429 savec = *cp;
1430 *cp = '\0';
1431 /* Add directory to search path */
1432 (void)Dir_AddDir(dirSearchPath, path);
1433 *cp = savec;
1434 path = cp + 1;
1435 } while (savec == ':');
1436 free(vpath);
1437 }
1438
1439 /*
1440 * Now that all search paths have been read for suffixes et al, it's
1441 * time to add the default search path to their lists...
1442 */
1443 Suff_DoPaths();
1444
1445 /*
1446 * Propagate attributes through :: dependency lists.
1447 */
1448 Targ_Propagate();
1449
1450 /* print the initial graph, if the user requested it */
1451 if (DEBUG(GRAPH1))
1452 Targ_PrintGraph(1);
1453
1454 /* print the values of any variables requested by the user */
1455 if (printVars) {
1456 doPrintVars();
1457 outOfDate = FALSE;
1458 } else {
1459 outOfDate = runTargets();
1460 }
1461
1462 #ifdef CLEANUP
1463 Lst_Free(variables);
1464 Lst_Free(makefiles);
1465 Lst_Destroy(create, free);
1466 #endif
1467
1468 /* print the graph now it's been processed if the user requested it */
1469 if (DEBUG(GRAPH2))
1470 Targ_PrintGraph(2);
1471
1472 Trace_Log(MAKEEND, 0);
1473
1474 if (enterFlagObj)
1475 printf("%s: Leaving directory `%s'\n", progname, objdir);
1476 if (enterFlag)
1477 printf("%s: Leaving directory `%s'\n", progname, curdir);
1478
1479 #ifdef USE_META
1480 meta_finish();
1481 #endif
1482 Suff_End();
1483 Targ_End();
1484 Arch_End();
1485 Var_End();
1486 Parse_End();
1487 Dir_End();
1488 Job_End();
1489 Trace_End();
1490
1491 return outOfDate ? 1 : 0;
1492 }
1493
1494 /* Open and parse the given makefile, with all its side effects.
1495 *
1496 * Results:
1497 * 0 if ok. -1 if couldn't open file.
1498 */
1499 static int
1500 ReadMakefile(const void *p, const void *q MAKE_ATTR_UNUSED)
1501 {
1502 const char *fname = p; /* makefile to read */
1503 int fd;
1504 char *name, *path = NULL;
1505
1506 if (!strcmp(fname, "-")) {
1507 Parse_File(NULL /*stdin*/, -1);
1508 Var_Set("MAKEFILE", "", VAR_INTERNAL);
1509 } else {
1510 /* if we've chdir'd, rebuild the path name */
1511 if (strcmp(curdir, objdir) && *fname != '/') {
1512 path = str_concat3(curdir, "/", fname);
1513 fd = open(path, O_RDONLY);
1514 if (fd != -1) {
1515 fname = path;
1516 goto found;
1517 }
1518 free(path);
1519
1520 /* If curdir failed, try objdir (ala .depend) */
1521 path = str_concat3(objdir, "/", fname);
1522 fd = open(path, O_RDONLY);
1523 if (fd != -1) {
1524 fname = path;
1525 goto found;
1526 }
1527 } else {
1528 fd = open(fname, O_RDONLY);
1529 if (fd != -1)
1530 goto found;
1531 }
1532 /* look in -I and system include directories. */
1533 name = Dir_FindFile(fname, parseIncPath);
1534 if (!name)
1535 name = Dir_FindFile(fname,
1536 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1537 if (!name || (fd = open(name, O_RDONLY)) == -1) {
1538 free(name);
1539 free(path);
1540 return -1;
1541 }
1542 fname = name;
1543 /*
1544 * set the MAKEFILE variable desired by System V fans -- the
1545 * placement of the setting here means it gets set to the last
1546 * makefile specified, as it is set by SysV make.
1547 */
1548 found:
1549 if (!doing_depend)
1550 Var_Set("MAKEFILE", fname, VAR_INTERNAL);
1551 Parse_File(fname, fd);
1552 }
1553 free(path);
1554 return 0;
1555 }
1556
1557
1558
1559 /*-
1560 * Cmd_Exec --
1561 * Execute the command in cmd, and return the output of that command
1562 * in a string. In the output, newlines are replaced with spaces.
1563 *
1564 * Results:
1565 * A string containing the output of the command, or the empty string.
1566 * *errfmt returns a format string describing the command failure,
1567 * if any, using a single %s conversion specification.
1568 *
1569 * Side Effects:
1570 * The string must be freed by the caller.
1571 */
1572 char *
1573 Cmd_Exec(const char *cmd, const char **errfmt)
1574 {
1575 const char *args[4]; /* Args for invoking the shell */
1576 int fds[2]; /* Pipe streams */
1577 int cpid; /* Child PID */
1578 int pid; /* PID from wait() */
1579 int status; /* command exit status */
1580 Buffer buf; /* buffer to store the result */
1581 ssize_t bytes_read;
1582 char *res; /* result */
1583 size_t res_len;
1584 char *cp;
1585 int savederr; /* saved errno */
1586
1587 *errfmt = NULL;
1588
1589 if (!shellName)
1590 Shell_Init();
1591 /*
1592 * Set up arguments for shell
1593 */
1594 args[0] = shellName;
1595 args[1] = "-c";
1596 args[2] = cmd;
1597 args[3] = NULL;
1598
1599 /*
1600 * Open a pipe for fetching its output
1601 */
1602 if (pipe(fds) == -1) {
1603 *errfmt = "Couldn't create pipe for \"%s\"";
1604 goto bad;
1605 }
1606
1607 /*
1608 * Fork
1609 */
1610 switch (cpid = vFork()) {
1611 case 0:
1612 /*
1613 * Close input side of pipe
1614 */
1615 (void)close(fds[0]);
1616
1617 /*
1618 * Duplicate the output stream to the shell's output, then
1619 * shut the extra thing down. Note we don't fetch the error
1620 * stream...why not? Why?
1621 */
1622 (void)dup2(fds[1], 1);
1623 (void)close(fds[1]);
1624
1625 Var_ExportVars();
1626
1627 (void)execv(shellPath, UNCONST(args));
1628 _exit(1);
1629 /*NOTREACHED*/
1630
1631 case -1:
1632 *errfmt = "Couldn't exec \"%s\"";
1633 goto bad;
1634
1635 default:
1636 /*
1637 * No need for the writing half
1638 */
1639 (void)close(fds[1]);
1640
1641 savederr = 0;
1642 Buf_Init(&buf, 0);
1643
1644 do {
1645 char result[BUFSIZ];
1646 bytes_read = read(fds[0], result, sizeof(result));
1647 if (bytes_read > 0)
1648 Buf_AddBytes(&buf, result, (size_t)bytes_read);
1649 }
1650 while (bytes_read > 0 || (bytes_read == -1 && errno == EINTR));
1651 if (bytes_read == -1)
1652 savederr = errno;
1653
1654 /*
1655 * Close the input side of the pipe.
1656 */
1657 (void)close(fds[0]);
1658
1659 /*
1660 * Wait for the process to exit.
1661 */
1662 while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) {
1663 JobReapChild(pid, status, FALSE);
1664 continue;
1665 }
1666 res_len = Buf_Size(&buf);
1667 res = Buf_Destroy(&buf, FALSE);
1668
1669 if (savederr != 0)
1670 *errfmt = "Couldn't read shell's output for \"%s\"";
1671
1672 if (WIFSIGNALED(status))
1673 *errfmt = "\"%s\" exited on a signal";
1674 else if (WEXITSTATUS(status) != 0)
1675 *errfmt = "\"%s\" returned non-zero status";
1676
1677 /* Convert newlines to spaces. A final newline is just stripped */
1678 if (res_len > 0 && res[res_len - 1] == '\n')
1679 res[res_len - 1] = '\0';
1680 for (cp = res; *cp != '\0'; cp++)
1681 if (*cp == '\n')
1682 *cp = ' ';
1683 break;
1684 }
1685 return res;
1686 bad:
1687 return bmake_strdup("");
1688 }
1689
1690 /*-
1691 * Error --
1692 * Print an error message given its format.
1693 *
1694 * Results:
1695 * None.
1696 *
1697 * Side Effects:
1698 * The message is printed.
1699 */
1700 /* VARARGS */
1701 void
1702 Error(const char *fmt, ...)
1703 {
1704 va_list ap;
1705 FILE *err_file;
1706
1707 err_file = debug_file;
1708 if (err_file == stdout)
1709 err_file = stderr;
1710 (void)fflush(stdout);
1711 for (;;) {
1712 va_start(ap, fmt);
1713 fprintf(err_file, "%s: ", progname);
1714 (void)vfprintf(err_file, fmt, ap);
1715 va_end(ap);
1716 (void)fprintf(err_file, "\n");
1717 (void)fflush(err_file);
1718 if (err_file == stderr)
1719 break;
1720 err_file = stderr;
1721 }
1722 }
1723
1724 /*-
1725 * Fatal --
1726 * Produce a Fatal error message. If jobs are running, waits for them
1727 * to finish.
1728 *
1729 * Results:
1730 * None
1731 *
1732 * Side Effects:
1733 * The program exits
1734 */
1735 /* VARARGS */
1736 void
1737 Fatal(const char *fmt, ...)
1738 {
1739 va_list ap;
1740
1741 va_start(ap, fmt);
1742 if (jobsRunning)
1743 Job_Wait();
1744
1745 (void)fflush(stdout);
1746 (void)vfprintf(stderr, fmt, ap);
1747 va_end(ap);
1748 (void)fprintf(stderr, "\n");
1749 (void)fflush(stderr);
1750
1751 PrintOnError(NULL, NULL);
1752
1753 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1754 Targ_PrintGraph(2);
1755 Trace_Log(MAKEERROR, 0);
1756 exit(2); /* Not 1 so -q can distinguish error */
1757 }
1758
1759 /*
1760 * Punt --
1761 * Major exception once jobs are being created. Kills all jobs, prints
1762 * a message and exits.
1763 *
1764 * Results:
1765 * None
1766 *
1767 * Side Effects:
1768 * All children are killed indiscriminately and the program Lib_Exits
1769 */
1770 /* VARARGS */
1771 void
1772 Punt(const char *fmt, ...)
1773 {
1774 va_list ap;
1775
1776 va_start(ap, fmt);
1777 (void)fflush(stdout);
1778 (void)fprintf(stderr, "%s: ", progname);
1779 (void)vfprintf(stderr, fmt, ap);
1780 va_end(ap);
1781 (void)fprintf(stderr, "\n");
1782 (void)fflush(stderr);
1783
1784 PrintOnError(NULL, NULL);
1785
1786 DieHorribly();
1787 }
1788
1789 /*-
1790 * DieHorribly --
1791 * Exit without giving a message.
1792 *
1793 * Results:
1794 * None
1795 *
1796 * Side Effects:
1797 * A big one...
1798 */
1799 void
1800 DieHorribly(void)
1801 {
1802 if (jobsRunning)
1803 Job_AbortAll();
1804 if (DEBUG(GRAPH2))
1805 Targ_PrintGraph(2);
1806 Trace_Log(MAKEERROR, 0);
1807 exit(2); /* Not 1, so -q can distinguish error */
1808 }
1809
1810 /*
1811 * Finish --
1812 * Called when aborting due to errors in child shell to signal
1813 * abnormal exit.
1814 *
1815 * Results:
1816 * None
1817 *
1818 * Side Effects:
1819 * The program exits
1820 */
1821 void
1822 Finish(int errors)
1823 /* number of errors encountered in Make_Make */
1824 {
1825 if (dieQuietly(NULL, -1))
1826 exit(2);
1827 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1828 }
1829
1830 /*
1831 * eunlink --
1832 * Remove a file carefully, avoiding directories.
1833 */
1834 int
1835 eunlink(const char *file)
1836 {
1837 struct stat st;
1838
1839 if (lstat(file, &st) == -1)
1840 return -1;
1841
1842 if (S_ISDIR(st.st_mode)) {
1843 errno = EISDIR;
1844 return -1;
1845 }
1846 return unlink(file);
1847 }
1848
1849 /*
1850 * execError --
1851 * Print why exec failed, avoiding stdio.
1852 */
1853 void
1854 execError(const char *af, const char *av)
1855 {
1856 #ifdef USE_IOVEC
1857 int i = 0;
1858 struct iovec iov[8];
1859 #define IOADD(s) \
1860 (void)(iov[i].iov_base = UNCONST(s), \
1861 iov[i].iov_len = strlen(iov[i].iov_base), \
1862 i++)
1863 #else
1864 #define IOADD(void)write(2, s, strlen(s))
1865 #endif
1866
1867 IOADD(progname);
1868 IOADD(": ");
1869 IOADD(af);
1870 IOADD("(");
1871 IOADD(av);
1872 IOADD(") failed (");
1873 IOADD(strerror(errno));
1874 IOADD(")\n");
1875
1876 #ifdef USE_IOVEC
1877 while (writev(2, iov, 8) == -1 && errno == EAGAIN)
1878 continue;
1879 #endif
1880 }
1881
1882 /*
1883 * usage --
1884 * exit with usage message
1885 */
1886 static void
1887 usage(void)
1888 {
1889 char *p;
1890 if ((p = strchr(progname, '[')) != NULL)
1891 *p = '\0';
1892
1893 (void)fprintf(stderr,
1894 "usage: %s [-BeikNnqrstWwX] \n"
1895 " [-C directory] [-D variable] [-d flags] [-f makefile]\n"
1896 " [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n"
1897 " [-V variable] [-v variable] [variable=value] [target ...]\n",
1898 progname);
1899 exit(2);
1900 }
1901
1902 /*
1903 * realpath(3) can get expensive, cache results...
1904 */
1905 static GNode *cached_realpaths = NULL;
1906
1907 static GNode *
1908 get_cached_realpaths(void)
1909 {
1910
1911 if (!cached_realpaths) {
1912 cached_realpaths = Targ_NewGN("Realpath");
1913 #ifndef DEBUG_REALPATH_CACHE
1914 cached_realpaths->flags = INTERNAL;
1915 #endif
1916 }
1917
1918 return cached_realpaths;
1919 }
1920
1921 /* purge any relative paths */
1922 static void
1923 purge_cached_realpaths(void)
1924 {
1925 GNode *cache = get_cached_realpaths();
1926 Hash_Entry *he, *nhe;
1927 Hash_Search hs;
1928
1929 he = Hash_EnumFirst(&cache->context, &hs);
1930 while (he) {
1931 nhe = Hash_EnumNext(&hs);
1932 if (he->name[0] != '/') {
1933 if (DEBUG(DIR))
1934 fprintf(stderr, "cached_realpath: purging %s\n", he->name);
1935 Hash_DeleteEntry(&cache->context, he);
1936 }
1937 he = nhe;
1938 }
1939 }
1940
1941 char *
1942 cached_realpath(const char *pathname, char *resolved)
1943 {
1944 GNode *cache;
1945 const char *rp;
1946 char *cp;
1947
1948 if (!pathname || !pathname[0])
1949 return NULL;
1950
1951 cache = get_cached_realpaths();
1952
1953 if ((rp = Var_Value(pathname, cache, &cp)) != NULL) {
1954 /* a hit */
1955 strncpy(resolved, rp, MAXPATHLEN);
1956 resolved[MAXPATHLEN - 1] = '\0';
1957 } else if ((rp = realpath(pathname, resolved)) != NULL) {
1958 Var_Set(pathname, rp, cache);
1959 } /* else should we negative-cache? */
1960
1961 bmake_free(cp);
1962 return rp ? resolved : NULL;
1963 }
1964
1965 int
1966 PrintAddr(void *a, void *b)
1967 {
1968 printf("%lx ", (unsigned long) a);
1969 return b ? 0 : 0;
1970 }
1971
1972
1973 static int
1974 addErrorCMD(void *cmdp, void *gnp)
1975 {
1976 if (cmdp == NULL)
1977 return 1; /* stop */
1978 Var_Append(".ERROR_CMD", cmdp, VAR_GLOBAL);
1979 return 0;
1980 }
1981
1982 /*
1983 * Return true if we should die without noise.
1984 * For example our failing child was a sub-make
1985 * or failure happend elsewhere.
1986 */
1987 int
1988 dieQuietly(GNode *gn, int bf)
1989 {
1990 static int quietly = -1;
1991
1992 if (quietly < 0) {
1993 if (DEBUG(JOB) || getBoolean(".MAKE.DIE_QUIETLY", 1) == 0)
1994 quietly = 0;
1995 else if (bf >= 0)
1996 quietly = bf;
1997 else
1998 quietly = (gn) ? ((gn->type & (OP_MAKE)) != 0) : 0;
1999 }
2000 return quietly;
2001 }
2002
2003 void
2004 PrintOnError(GNode *gn, const char *s)
2005 {
2006 static GNode *en = NULL;
2007 const char *expr;
2008 char *cp;
2009
2010 if (DEBUG(HASH)) {
2011 Targ_Stats();
2012 Var_Stats();
2013 }
2014
2015 /* we generally want to keep quiet if a sub-make died */
2016 if (dieQuietly(gn, -1))
2017 return;
2018
2019 if (s)
2020 printf("%s", s);
2021
2022 printf("\n%s: stopped in %s\n", progname, curdir);
2023
2024 if (en)
2025 return; /* we've been here! */
2026 if (gn) {
2027 /*
2028 * We can print this even if there is no .ERROR target.
2029 */
2030 Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL);
2031 Var_Delete(".ERROR_CMD", VAR_GLOBAL);
2032 Lst_ForEach(gn->commands, addErrorCMD, gn);
2033 }
2034 expr = "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}";
2035 cp = Var_Subst(expr, VAR_GLOBAL, VARE_WANTRES);
2036 if (cp) {
2037 if (*cp)
2038 printf("%s", cp);
2039 free(cp);
2040 }
2041 fflush(stdout);
2042
2043 /*
2044 * Finally, see if there is a .ERROR target, and run it if so.
2045 */
2046 en = Targ_FindNode(".ERROR", TARG_NOCREATE);
2047 if (en) {
2048 en->type |= OP_SPECIAL;
2049 Compat_Make(en, en);
2050 }
2051 }
2052
2053 void
2054 Main_ExportMAKEFLAGS(Boolean first)
2055 {
2056 static int once = 1;
2057 const char *expr;
2058 char *s;
2059
2060 if (once != first)
2061 return;
2062 once = 0;
2063
2064 expr = "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}";
2065 s = Var_Subst(expr, VAR_CMD, VARE_WANTRES);
2066 if (s != NULL && s[0] != '\0') {
2067 #ifdef POSIX
2068 setenv("MAKEFLAGS", s, 1);
2069 #else
2070 setenv("MAKE", s, 1);
2071 #endif
2072 }
2073 }
2074
2075 char *
2076 getTmpdir(void)
2077 {
2078 static char *tmpdir = NULL;
2079
2080 if (!tmpdir) {
2081 struct stat st;
2082
2083 /*
2084 * Honor $TMPDIR but only if it is valid.
2085 * Ensure it ends with /.
2086 */
2087 tmpdir = Var_Subst("${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL,
2088 VARE_WANTRES);
2089 if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
2090 free(tmpdir);
2091 tmpdir = bmake_strdup(_PATH_TMP);
2092 }
2093 }
2094 return tmpdir;
2095 }
2096
2097 /*
2098 * Create and open a temp file using "pattern".
2099 * If "fnamep" is provided set it to a copy of the filename created.
2100 * Otherwise unlink the file once open.
2101 */
2102 int
2103 mkTempFile(const char *pattern, char **fnamep)
2104 {
2105 static char *tmpdir = NULL;
2106 char tfile[MAXPATHLEN];
2107 int fd;
2108
2109 if (!pattern)
2110 pattern = TMPPAT;
2111 if (!tmpdir)
2112 tmpdir = getTmpdir();
2113 if (pattern[0] == '/') {
2114 snprintf(tfile, sizeof(tfile), "%s", pattern);
2115 } else {
2116 snprintf(tfile, sizeof(tfile), "%s%s", tmpdir, pattern);
2117 }
2118 if ((fd = mkstemp(tfile)) < 0)
2119 Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
2120 if (fnamep) {
2121 *fnamep = bmake_strdup(tfile);
2122 } else {
2123 unlink(tfile); /* we just want the descriptor */
2124 }
2125 return fd;
2126 }
2127
2128 /*
2129 * Convert a string representation of a boolean.
2130 * Anything that looks like "No", "False", "Off", "0" etc,
2131 * is FALSE, otherwise TRUE.
2132 */
2133 Boolean
2134 s2Boolean(const char *s, Boolean bf)
2135 {
2136 if (s) {
2137 switch(*s) {
2138 case '\0': /* not set - the default wins */
2139 break;
2140 case '0':
2141 case 'F':
2142 case 'f':
2143 case 'N':
2144 case 'n':
2145 bf = FALSE;
2146 break;
2147 case 'O':
2148 case 'o':
2149 switch (s[1]) {
2150 case 'F':
2151 case 'f':
2152 bf = FALSE;
2153 break;
2154 default:
2155 bf = TRUE;
2156 break;
2157 }
2158 break;
2159 default:
2160 bf = TRUE;
2161 break;
2162 }
2163 }
2164 return bf;
2165 }
2166
2167 /*
2168 * Return a Boolean based on setting of a knob.
2169 *
2170 * If the knob is not set, the supplied default is the return value.
2171 * If set, anything that looks or smells like "No", "False", "Off", "0" etc,
2172 * is FALSE, otherwise TRUE.
2173 */
2174 Boolean
2175 getBoolean(const char *name, Boolean bf)
2176 {
2177 char tmp[64];
2178 char *cp;
2179
2180 if (snprintf(tmp, sizeof(tmp), "${%s:U:tl}", name) < (int)(sizeof(tmp))) {
2181 cp = Var_Subst(tmp, VAR_GLOBAL, VARE_WANTRES);
2182
2183 if (cp) {
2184 bf = s2Boolean(cp, bf);
2185 free(cp);
2186 }
2187 }
2188 return bf;
2189 }
2190