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