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