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