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