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