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