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