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