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