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