main.c revision 1.383 1 /* $NetBSD: main.c,v 1.383 2020/10/22 07:01:25 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.383 2020/10/22 07:01:25 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 int 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, for Lst_Find. */
795 static Boolean
796 ReadMakefileSucceeded(const void *fname, const void *unused)
797 {
798 return ReadMakefile(fname) == 0;
799 }
800
801 /* Read and parse the makefile.
802 * Return TRUE if reading the makefile failed, for Lst_Find. */
803 static Boolean
804 ReadMakefileFailed(const void *fname, const void *unused)
805 {
806 return ReadMakefile(fname) != 0;
807 }
808
809 int
810 str2Lst_Append(StringList *lp, char *str, const char *sep)
811 {
812 char *cp;
813 int n;
814
815 if (!sep)
816 sep = " \t";
817
818 for (n = 0, cp = strtok(str, sep); cp; cp = strtok(NULL, sep)) {
819 Lst_Append(lp, cp);
820 n++;
821 }
822 return n;
823 }
824
825 #ifdef SIGINFO
826 /*ARGSUSED*/
827 static void
828 siginfo(int signo MAKE_ATTR_UNUSED)
829 {
830 char dir[MAXPATHLEN];
831 char str[2 * MAXPATHLEN];
832 int len;
833 if (getcwd(dir, sizeof(dir)) == NULL)
834 return;
835 len = snprintf(str, sizeof(str), "%s: Working in: %s\n", progname, dir);
836 if (len > 0)
837 (void)write(STDERR_FILENO, str, (size_t)len);
838 }
839 #endif
840
841 /*
842 * Allow makefiles some control over the mode we run in.
843 */
844 void
845 MakeMode(const char *mode)
846 {
847 char *mode_freeIt = NULL;
848
849 if (mode == NULL) {
850 (void)Var_Subst("${" MAKE_MODE ":tl}",
851 VAR_GLOBAL, VARE_WANTRES, &mode_freeIt);
852 /* TODO: handle errors */
853 mode = mode_freeIt;
854 }
855
856 if (mode[0] != '\0') {
857 if (strstr(mode, "compat")) {
858 compatMake = TRUE;
859 forceJobs = FALSE;
860 }
861 #if USE_META
862 if (strstr(mode, "meta"))
863 meta_mode_init(mode);
864 #endif
865 }
866
867 free(mode_freeIt);
868 }
869
870 static void
871 PrintVar(const char *varname, Boolean expandVars)
872 {
873 const char *value;
874 char *p1;
875
876 if (strchr(varname, '$')) {
877 (void)Var_Subst(varname, VAR_GLOBAL, VARE_WANTRES, &p1);
878 /* TODO: handle errors */
879 value = p1;
880 } else if (expandVars) {
881 char *expr = str_concat3("${", varname, "}");
882 (void)Var_Subst(expr, VAR_GLOBAL, VARE_WANTRES, &p1);
883 /* TODO: handle errors */
884 value = p1;
885 free(expr);
886 } else {
887 value = Var_Value(varname, VAR_GLOBAL, &p1);
888 }
889 printf("%s\n", value ? value : "");
890 bmake_free(p1);
891 }
892
893 static void
894 doPrintVars(void)
895 {
896 StringListNode *ln;
897 Boolean expandVars;
898
899 if (printVars == EXPAND_VARS)
900 expandVars = TRUE;
901 else if (debugVflag)
902 expandVars = FALSE;
903 else
904 expandVars = getBoolean(".MAKE.EXPAND_VARIABLES", FALSE);
905
906 for (ln = variables->first; ln != NULL; ln = ln->next) {
907 const char *varname = ln->datum;
908 PrintVar(varname, expandVars);
909 }
910 }
911
912 static Boolean
913 runTargets(void)
914 {
915 GNodeList *targs; /* target nodes to create -- passed to Make_Init */
916 Boolean outOfDate; /* FALSE if all targets up to date */
917
918 /*
919 * Have now read the entire graph and need to make a list of
920 * targets to create. If none was given on the command line,
921 * we consult the parsing module to find the main target(s)
922 * to create.
923 */
924 if (Lst_IsEmpty(create))
925 targs = Parse_MainName();
926 else
927 targs = Targ_FindList(create);
928
929 if (!compatMake) {
930 /*
931 * Initialize job module before traversing the graph
932 * now that any .BEGIN and .END targets have been read.
933 * This is done only if the -q flag wasn't given
934 * (to prevent the .BEGIN from being executed should
935 * it exist).
936 */
937 if (!queryFlag) {
938 Job_Init();
939 jobsRunning = TRUE;
940 }
941
942 /* Traverse the graph, checking on all the targets */
943 outOfDate = Make_Run(targs);
944 } else {
945 /*
946 * Compat_Init will take care of creating all the
947 * targets as well as initializing the module.
948 */
949 Compat_Run(targs);
950 outOfDate = FALSE;
951 }
952 Lst_Free(targs);
953 return outOfDate;
954 }
955
956 /*
957 * Set up the .TARGETS variable to contain the list of targets to be
958 * created. If none specified, make the variable empty -- the parser
959 * will fill the thing in with the default or .MAIN target.
960 */
961 static void
962 InitVarTargets(void)
963 {
964 StringListNode *ln;
965
966 if (Lst_IsEmpty(create)) {
967 Var_Set(".TARGETS", "", VAR_GLOBAL);
968 return;
969 }
970
971 for (ln = create->first; ln != NULL; ln = ln->next) {
972 char *name = ln->datum;
973 Var_Append(".TARGETS", name, VAR_GLOBAL);
974 }
975 }
976
977 static const char *
978 init_machine(const struct utsname *utsname)
979 {
980 const char *machine = getenv("MACHINE");
981 if (machine != NULL)
982 return machine;
983
984 #ifdef MAKE_NATIVE
985 return utsname->machine;
986 #else
987 #ifdef MAKE_MACHINE
988 return MAKE_MACHINE;
989 #else
990 return "unknown";
991 #endif
992 #endif
993 }
994
995 static const char *
996 init_machine_arch(void)
997 {
998 const char *env = getenv("MACHINE_ARCH");
999 if (env != NULL)
1000 return env;
1001
1002 #ifdef MAKE_NATIVE
1003 {
1004 struct utsname utsname;
1005 static char machine_arch_buf[sizeof(utsname.machine)];
1006 const int mib[2] = { CTL_HW, HW_MACHINE_ARCH };
1007 size_t len = sizeof(machine_arch_buf);
1008
1009 if (sysctl(mib, __arraycount(mib), machine_arch_buf,
1010 &len, NULL, 0) < 0) {
1011 (void)fprintf(stderr, "%s: sysctl failed (%s).\n", progname,
1012 strerror(errno));
1013 exit(2);
1014 }
1015
1016 return machine_arch_buf;
1017 }
1018 #else
1019 #ifndef MACHINE_ARCH
1020 #ifdef MAKE_MACHINE_ARCH
1021 return MAKE_MACHINE_ARCH;
1022 #else
1023 return "unknown";
1024 #endif
1025 #else
1026 return MACHINE_ARCH;
1027 #endif
1028 #endif
1029 }
1030
1031 #ifndef NO_PWD_OVERRIDE
1032 /*
1033 * All this code is so that we know where we are when we start up
1034 * on a different machine with pmake.
1035 *
1036 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
1037 * since the value of curdir can vary depending on how we got
1038 * here. Ie sitting at a shell prompt (shell that provides $PWD)
1039 * or via subdir.mk in which case its likely a shell which does
1040 * not provide it.
1041 *
1042 * So, to stop it breaking this case only, we ignore PWD if
1043 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a variable expression.
1044 */
1045 static void
1046 HandlePWD(const struct stat *curdir_st)
1047 {
1048 char *pwd;
1049 char *prefix_freeIt, *makeobjdir_freeIt;
1050 const char *makeobjdir;
1051 struct stat pwd_st;
1052
1053 if (ignorePWD || (pwd = getenv("PWD")) == NULL)
1054 return;
1055
1056 if (Var_Value("MAKEOBJDIRPREFIX", VAR_CMD, &prefix_freeIt) != NULL) {
1057 bmake_free(prefix_freeIt);
1058 return;
1059 }
1060
1061 makeobjdir = Var_Value("MAKEOBJDIR", VAR_CMD, &makeobjdir_freeIt);
1062 if (makeobjdir != NULL && strchr(makeobjdir, '$') != NULL)
1063 goto ignore_pwd;
1064
1065 if (stat(pwd, &pwd_st) == 0 &&
1066 curdir_st->st_ino == pwd_st.st_ino &&
1067 curdir_st->st_dev == pwd_st.st_dev)
1068 (void)strncpy(curdir, pwd, MAXPATHLEN);
1069
1070 ignore_pwd:
1071 bmake_free(makeobjdir_freeIt);
1072 }
1073 #endif
1074
1075 /*-
1076 * main --
1077 * The main function, for obvious reasons. Initializes variables
1078 * and a few modules, then parses the arguments give it in the
1079 * environment and on the command line. Reads the system makefile
1080 * followed by either Makefile, makefile or the file given by the
1081 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
1082 * flags it has received by then uses either the Make or the Compat
1083 * module to create the initial list of targets.
1084 *
1085 * Results:
1086 * If -q was given, exits -1 if anything was out-of-date. Else it exits
1087 * 0.
1088 *
1089 * Side Effects:
1090 * The program exits when done. Targets are created. etc. etc. etc.
1091 */
1092 int
1093 main(int argc, char **argv)
1094 {
1095 Boolean outOfDate; /* FALSE if all targets up to date */
1096 struct stat sa;
1097 char *p1, *path;
1098 char mdpath[MAXPATHLEN];
1099 const char *machine;
1100 const char *machine_arch;
1101 char *syspath = getenv("MAKESYSPATH");
1102 StringList *sysMkPath; /* Path of sys.mk */
1103 char *cp = NULL, *start;
1104 /* avoid faults on read-only strings */
1105 static char defsyspath[] = _PATH_DEFSYSPATH;
1106 struct timeval rightnow; /* to initialize random seed */
1107 struct utsname utsname;
1108
1109 /* default to writing debug to stderr */
1110 debug_file = stderr;
1111
1112 #ifdef SIGINFO
1113 (void)bmake_signal(SIGINFO, siginfo);
1114 #endif
1115 /*
1116 * Set the seed to produce a different random sequence
1117 * on each program execution.
1118 */
1119 gettimeofday(&rightnow, NULL);
1120 srandom((unsigned int)(rightnow.tv_sec + rightnow.tv_usec));
1121
1122 if ((progname = strrchr(argv[0], '/')) != NULL)
1123 progname++;
1124 else
1125 progname = argv[0];
1126 #if defined(MAKE_NATIVE) || (defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE))
1127 /*
1128 * get rid of resource limit on file descriptors
1129 */
1130 {
1131 struct rlimit rl;
1132 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
1133 rl.rlim_cur != rl.rlim_max) {
1134 rl.rlim_cur = rl.rlim_max;
1135 (void)setrlimit(RLIMIT_NOFILE, &rl);
1136 }
1137 }
1138 #endif
1139
1140 if (uname(&utsname) == -1) {
1141 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
1142 strerror(errno));
1143 exit(2);
1144 }
1145
1146 /*
1147 * Get the name of this type of MACHINE from utsname
1148 * so we can share an executable for similar machines.
1149 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
1150 *
1151 * Note that both MACHINE and MACHINE_ARCH are decided at
1152 * run-time.
1153 */
1154 machine = init_machine(&utsname);
1155 machine_arch = init_machine_arch();
1156
1157 myPid = getpid(); /* remember this for vFork() */
1158
1159 /*
1160 * Just in case MAKEOBJDIR wants us to do something tricky.
1161 */
1162 Var_Init(); /* Initialize the lists of variables for
1163 * parsing arguments */
1164 Var_Set(".MAKE.OS", utsname.sysname, VAR_GLOBAL);
1165 Var_Set("MACHINE", machine, VAR_GLOBAL);
1166 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
1167 #ifdef MAKE_VERSION
1168 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
1169 #endif
1170 Var_Set(".newline", "\n", VAR_GLOBAL); /* handy for :@ loops */
1171 /*
1172 * This is the traditional preference for makefiles.
1173 */
1174 #ifndef MAKEFILE_PREFERENCE_LIST
1175 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
1176 #endif
1177 Var_Set(MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST,
1178 VAR_GLOBAL);
1179 Var_Set(MAKE_DEPENDFILE, ".depend", VAR_GLOBAL);
1180
1181 create = Lst_New();
1182 makefiles = Lst_New();
1183 printVars = 0;
1184 debugVflag = FALSE;
1185 variables = Lst_New();
1186 beSilent = FALSE; /* Print commands as executed */
1187 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
1188 noExecute = FALSE; /* Execute all commands */
1189 noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
1190 keepgoing = FALSE; /* Stop on error */
1191 allPrecious = FALSE; /* Remove targets when interrupted */
1192 deleteOnError = FALSE; /* Historical default behavior */
1193 queryFlag = FALSE; /* This is not just a check-run */
1194 noBuiltins = FALSE; /* Read the built-in rules */
1195 touchFlag = FALSE; /* Actually update targets */
1196 debug = 0; /* No debug verbosity, please. */
1197 jobsRunning = FALSE;
1198
1199 maxJobs = DEFMAXLOCAL; /* Set default local max concurrency */
1200 maxJobTokens = maxJobs;
1201 compatMake = FALSE; /* No compat mode */
1202 ignorePWD = FALSE;
1203
1204 /*
1205 * Initialize the parsing, directory and variable modules to prepare
1206 * for the reading of inclusion paths and variable settings on the
1207 * command line
1208 */
1209
1210 /*
1211 * Initialize various variables.
1212 * MAKE also gets this name, for compatibility
1213 * .MAKEFLAGS gets set to the empty string just in case.
1214 * MFLAGS also gets initialized empty, for compatibility.
1215 */
1216 Parse_Init();
1217 if (argv[0][0] == '/' || strchr(argv[0], '/') == NULL) {
1218 /*
1219 * Leave alone if it is an absolute path, or if it does
1220 * not contain a '/' in which case we need to find it in
1221 * the path, like execvp(3) and the shells do.
1222 */
1223 p1 = argv[0];
1224 } else {
1225 struct stat sb;
1226 /*
1227 * A relative path, canonicalize it.
1228 */
1229 p1 = cached_realpath(argv[0], mdpath);
1230 if (!p1 || *p1 != '/' || stat(p1, &sb) < 0) {
1231 p1 = argv[0]; /* realpath failed */
1232 }
1233 }
1234 Var_Set("MAKE", p1, VAR_GLOBAL);
1235 Var_Set(".MAKE", p1, VAR_GLOBAL);
1236 Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
1237 Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL);
1238 Var_Set("MFLAGS", "", VAR_GLOBAL);
1239 Var_Set(".ALLTARGETS", "", VAR_GLOBAL);
1240 /* some makefiles need to know this */
1241 Var_Set(MAKE_LEVEL ".ENV", MAKE_LEVEL_ENV, VAR_CMD);
1242
1243 /*
1244 * Set some other useful macros
1245 */
1246 {
1247 char tmp[64], *ep;
1248
1249 makelevel = ((ep = getenv(MAKE_LEVEL_ENV)) && *ep) ? atoi(ep) : 0;
1250 if (makelevel < 0)
1251 makelevel = 0;
1252 snprintf(tmp, sizeof(tmp), "%d", makelevel);
1253 Var_Set(MAKE_LEVEL, tmp, VAR_GLOBAL);
1254 snprintf(tmp, sizeof(tmp), "%u", myPid);
1255 Var_Set(".MAKE.PID", tmp, VAR_GLOBAL);
1256 snprintf(tmp, sizeof(tmp), "%u", getppid());
1257 Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL);
1258 }
1259 if (makelevel > 0) {
1260 char pn[1024];
1261 snprintf(pn, sizeof(pn), "%s[%d]", progname, makelevel);
1262 progname = bmake_strdup(pn);
1263 }
1264
1265 #ifdef USE_META
1266 meta_init();
1267 #endif
1268 Dir_Init();
1269
1270 /*
1271 * First snag any flags out of the MAKE environment variable.
1272 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
1273 * in a different format).
1274 */
1275 #ifdef POSIX
1276 p1 = explode(getenv("MAKEFLAGS"));
1277 Main_ParseArgLine(p1);
1278 free(p1);
1279 #else
1280 Main_ParseArgLine(getenv("MAKE"));
1281 #endif
1282
1283 /*
1284 * Find where we are (now).
1285 * We take care of PWD for the automounter below...
1286 */
1287 if (getcwd(curdir, MAXPATHLEN) == NULL) {
1288 (void)fprintf(stderr, "%s: getcwd: %s.\n",
1289 progname, strerror(errno));
1290 exit(2);
1291 }
1292
1293 MainParseArgs(argc, argv);
1294
1295 if (enterFlag)
1296 printf("%s: Entering directory `%s'\n", progname, curdir);
1297
1298 /*
1299 * Verify that cwd is sane.
1300 */
1301 if (stat(curdir, &sa) == -1) {
1302 (void)fprintf(stderr, "%s: %s: %s.\n",
1303 progname, curdir, strerror(errno));
1304 exit(2);
1305 }
1306
1307 #ifndef NO_PWD_OVERRIDE
1308 HandlePWD(&sa);
1309 #endif
1310 Var_Set(".CURDIR", curdir, VAR_GLOBAL);
1311
1312 /*
1313 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
1314 * MAKEOBJDIR is set in the environment, try only that value
1315 * and fall back to .CURDIR if it does not exist.
1316 *
1317 * Otherwise, try _PATH_OBJDIR.MACHINE-MACHINE_ARCH, _PATH_OBJDIR.MACHINE,
1318 * and * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
1319 * of these paths exist, just use .CURDIR.
1320 */
1321 Dir_InitDir(curdir);
1322 (void)Main_SetObjdir("%s", curdir);
1323
1324 if (!Main_SetVarObjdir("MAKEOBJDIRPREFIX", curdir) &&
1325 !Main_SetVarObjdir("MAKEOBJDIR", "") &&
1326 !Main_SetObjdir("%s.%s-%s", _PATH_OBJDIR, machine, machine_arch) &&
1327 !Main_SetObjdir("%s.%s", _PATH_OBJDIR, machine) &&
1328 !Main_SetObjdir("%s", _PATH_OBJDIR))
1329 (void)Main_SetObjdir("%s%s", _PATH_OBJDIRPREFIX, curdir);
1330
1331 /*
1332 * Initialize archive, target and suffix modules in preparation for
1333 * parsing the makefile(s)
1334 */
1335 Arch_Init();
1336 Targ_Init();
1337 Suff_Init();
1338 Trace_Init(tracefile);
1339
1340 DEFAULT = NULL;
1341 (void)time(&now);
1342
1343 Trace_Log(MAKESTART, NULL);
1344
1345 InitVarTargets();
1346
1347 /*
1348 * If no user-supplied system path was given (through the -m option)
1349 * add the directories from the DEFSYSPATH (more than one may be given
1350 * as dir1:...:dirn) to the system include path.
1351 */
1352 /* XXX: mismatch: the -m option sets sysIncPath, not syspath */
1353 if (syspath == NULL || syspath[0] == '\0')
1354 syspath = defsyspath;
1355 else
1356 syspath = bmake_strdup(syspath);
1357
1358 for (start = syspath; *start != '\0'; start = cp) {
1359 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1360 continue;
1361 if (*cp == ':') {
1362 *cp++ = '\0';
1363 }
1364 /* look for magic parent directory search string */
1365 if (strncmp(".../", start, 4) != 0) {
1366 (void)Dir_AddDir(defIncPath, start);
1367 } else {
1368 char *dir = Dir_FindHereOrAbove(curdir, start + 4);
1369 if (dir != NULL) {
1370 (void)Dir_AddDir(defIncPath, dir);
1371 free(dir);
1372 }
1373 }
1374 }
1375 if (syspath != defsyspath)
1376 free(syspath);
1377
1378 /*
1379 * Read in the built-in rules first, followed by the specified
1380 * makefiles, or the default makefile and Makefile, in that order,
1381 * if no makefiles were given on the command line.
1382 */
1383 if (!noBuiltins) {
1384 StringListNode *ln;
1385
1386 sysMkPath = Lst_New();
1387 Dir_Expand(_PATH_DEFSYSMK,
1388 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
1389 sysMkPath);
1390 if (Lst_IsEmpty(sysMkPath))
1391 Fatal("%s: no system rules (%s).", progname,
1392 _PATH_DEFSYSMK);
1393 ln = Lst_Find(sysMkPath, ReadMakefileSucceeded, NULL);
1394 if (ln == NULL)
1395 Fatal("%s: cannot open %s.", progname,
1396 (char *)sysMkPath->first->datum);
1397 }
1398
1399 if (!Lst_IsEmpty(makefiles)) {
1400 StringListNode *ln;
1401
1402 ln = Lst_Find(makefiles, ReadMakefileFailed, NULL);
1403 if (ln != NULL)
1404 Fatal("%s: cannot open %s.", progname,
1405 (char *)ln->datum);
1406 } else {
1407 (void)Var_Subst("${" MAKEFILE_PREFERENCE "}",
1408 VAR_CMD, VARE_WANTRES, &p1);
1409 /* TODO: handle errors */
1410 (void)str2Lst_Append(makefiles, p1, NULL);
1411 (void)Lst_Find(makefiles, ReadMakefileSucceeded, NULL);
1412 free(p1);
1413 }
1414
1415 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1416 if (!noBuiltins || !printVars) {
1417 (void)Var_Subst("${.MAKE.DEPENDFILE:T}",
1418 VAR_CMD, VARE_WANTRES, &makeDependfile);
1419 /* TODO: handle errors */
1420 doing_depend = TRUE;
1421 (void)ReadMakefile(makeDependfile);
1422 doing_depend = FALSE;
1423 }
1424
1425 if (enterFlagObj)
1426 printf("%s: Entering directory `%s'\n", progname, objdir);
1427
1428 MakeMode(NULL);
1429
1430 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
1431 bmake_free(p1);
1432
1433 if (!forceJobs && !compatMake &&
1434 Var_Exists(".MAKE.JOBS", VAR_GLOBAL)) {
1435 char *value;
1436 int n;
1437
1438 (void)Var_Subst("${.MAKE.JOBS}", VAR_GLOBAL, VARE_WANTRES, &value);
1439 /* TODO: handle errors */
1440 n = (int)strtol(value, NULL, 0);
1441 if (n < 1) {
1442 (void)fprintf(stderr, "%s: illegal value for .MAKE.JOBS -- must be positive integer!\n",
1443 progname);
1444 exit(1);
1445 }
1446 if (n != maxJobs) {
1447 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
1448 Var_Append(MAKEFLAGS, value, VAR_GLOBAL);
1449 }
1450 maxJobs = n;
1451 maxJobTokens = maxJobs;
1452 forceJobs = TRUE;
1453 free(value);
1454 }
1455
1456 /*
1457 * Be compatible if user did not specify -j and did not explicitly
1458 * turned compatibility on
1459 */
1460 if (!compatMake && !forceJobs) {
1461 compatMake = TRUE;
1462 }
1463
1464 if (!compatMake)
1465 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1466 DEBUG5(JOB, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1467 jp_0, jp_1, maxJobs, maxJobTokens, compatMake ? 1 : 0);
1468
1469 if (!printVars)
1470 Main_ExportMAKEFLAGS(TRUE); /* initial export */
1471
1472
1473 /*
1474 * For compatibility, look at the directories in the VPATH variable
1475 * and add them to the search path, if the variable is defined. The
1476 * variable's value is in the same format as the PATH envariable, i.e.
1477 * <directory>:<directory>:<directory>...
1478 */
1479 if (Var_Exists("VPATH", VAR_CMD)) {
1480 char *vpath, savec;
1481 /*
1482 * GCC stores string constants in read-only memory, but
1483 * Var_Subst will want to write this thing, so store it
1484 * in an array
1485 */
1486 static char VPATH[] = "${VPATH}";
1487
1488 (void)Var_Subst(VPATH, VAR_CMD, VARE_WANTRES, &vpath);
1489 /* TODO: handle errors */
1490 path = vpath;
1491 do {
1492 /* skip to end of directory */
1493 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1494 continue;
1495 /* Save terminator character so know when to stop */
1496 savec = *cp;
1497 *cp = '\0';
1498 /* Add directory to search path */
1499 (void)Dir_AddDir(dirSearchPath, path);
1500 *cp = savec;
1501 path = cp + 1;
1502 } while (savec == ':');
1503 free(vpath);
1504 }
1505
1506 /*
1507 * Now that all search paths have been read for suffixes et al, it's
1508 * time to add the default search path to their lists...
1509 */
1510 Suff_DoPaths();
1511
1512 /*
1513 * Propagate attributes through :: dependency lists.
1514 */
1515 Targ_Propagate();
1516
1517 /* print the initial graph, if the user requested it */
1518 if (DEBUG(GRAPH1))
1519 Targ_PrintGraph(1);
1520
1521 /* print the values of any variables requested by the user */
1522 if (printVars) {
1523 doPrintVars();
1524 outOfDate = FALSE;
1525 } else {
1526 outOfDate = runTargets();
1527 }
1528
1529 #ifdef CLEANUP
1530 Lst_Free(variables);
1531 Lst_Free(makefiles);
1532 Lst_Destroy(create, free);
1533 #endif
1534
1535 /* print the graph now it's been processed if the user requested it */
1536 if (DEBUG(GRAPH2))
1537 Targ_PrintGraph(2);
1538
1539 Trace_Log(MAKEEND, 0);
1540
1541 if (enterFlagObj)
1542 printf("%s: Leaving directory `%s'\n", progname, objdir);
1543 if (enterFlag)
1544 printf("%s: Leaving directory `%s'\n", progname, curdir);
1545
1546 #ifdef USE_META
1547 meta_finish();
1548 #endif
1549 Suff_End();
1550 Targ_End();
1551 Arch_End();
1552 Var_End();
1553 Parse_End();
1554 Dir_End();
1555 Job_End();
1556 Trace_End();
1557
1558 return outOfDate ? 1 : 0;
1559 }
1560
1561 /* Open and parse the given makefile, with all its side effects.
1562 *
1563 * Results:
1564 * 0 if ok. -1 if couldn't open file.
1565 */
1566 static int
1567 ReadMakefile(const char *fname)
1568 {
1569 int fd;
1570 char *name, *path = NULL;
1571
1572 if (!strcmp(fname, "-")) {
1573 Parse_File(NULL /*stdin*/, -1);
1574 Var_Set("MAKEFILE", "", VAR_INTERNAL);
1575 } else {
1576 /* if we've chdir'd, rebuild the path name */
1577 if (strcmp(curdir, objdir) && *fname != '/') {
1578 path = str_concat3(curdir, "/", fname);
1579 fd = open(path, O_RDONLY);
1580 if (fd != -1) {
1581 fname = path;
1582 goto found;
1583 }
1584 free(path);
1585
1586 /* If curdir failed, try objdir (ala .depend) */
1587 path = str_concat3(objdir, "/", fname);
1588 fd = open(path, O_RDONLY);
1589 if (fd != -1) {
1590 fname = path;
1591 goto found;
1592 }
1593 } else {
1594 fd = open(fname, O_RDONLY);
1595 if (fd != -1)
1596 goto found;
1597 }
1598 /* look in -I and system include directories. */
1599 name = Dir_FindFile(fname, parseIncPath);
1600 if (!name)
1601 name = Dir_FindFile(fname,
1602 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1603 if (!name || (fd = open(name, O_RDONLY)) == -1) {
1604 free(name);
1605 free(path);
1606 return -1;
1607 }
1608 fname = name;
1609 /*
1610 * set the MAKEFILE variable desired by System V fans -- the
1611 * placement of the setting here means it gets set to the last
1612 * makefile specified, as it is set by SysV make.
1613 */
1614 found:
1615 if (!doing_depend)
1616 Var_Set("MAKEFILE", fname, VAR_INTERNAL);
1617 Parse_File(fname, fd);
1618 }
1619 free(path);
1620 return 0;
1621 }
1622
1623
1624
1625 /*-
1626 * Cmd_Exec --
1627 * Execute the command in cmd, and return the output of that command
1628 * in a string. In the output, newlines are replaced with spaces.
1629 *
1630 * Results:
1631 * A string containing the output of the command, or the empty string.
1632 * *errfmt returns a format string describing the command failure,
1633 * if any, using a single %s conversion specification.
1634 *
1635 * Side Effects:
1636 * The string must be freed by the caller.
1637 */
1638 char *
1639 Cmd_Exec(const char *cmd, const char **errfmt)
1640 {
1641 const char *args[4]; /* Args for invoking the shell */
1642 int fds[2]; /* Pipe streams */
1643 int cpid; /* Child PID */
1644 int pid; /* PID from wait() */
1645 int status; /* command exit status */
1646 Buffer buf; /* buffer to store the result */
1647 ssize_t bytes_read;
1648 char *res; /* result */
1649 size_t res_len;
1650 char *cp;
1651 int savederr; /* saved errno */
1652
1653 *errfmt = NULL;
1654
1655 if (!shellName)
1656 Shell_Init();
1657 /*
1658 * Set up arguments for shell
1659 */
1660 args[0] = shellName;
1661 args[1] = "-c";
1662 args[2] = cmd;
1663 args[3] = NULL;
1664
1665 /*
1666 * Open a pipe for fetching its output
1667 */
1668 if (pipe(fds) == -1) {
1669 *errfmt = "Couldn't create pipe for \"%s\"";
1670 goto bad;
1671 }
1672
1673 /*
1674 * Fork
1675 */
1676 switch (cpid = vFork()) {
1677 case 0:
1678 /*
1679 * Close input side of pipe
1680 */
1681 (void)close(fds[0]);
1682
1683 /*
1684 * Duplicate the output stream to the shell's output, then
1685 * shut the extra thing down. Note we don't fetch the error
1686 * stream...why not? Why?
1687 */
1688 (void)dup2(fds[1], 1);
1689 (void)close(fds[1]);
1690
1691 Var_ExportVars();
1692
1693 (void)execv(shellPath, UNCONST(args));
1694 _exit(1);
1695 /*NOTREACHED*/
1696
1697 case -1:
1698 *errfmt = "Couldn't exec \"%s\"";
1699 goto bad;
1700
1701 default:
1702 /*
1703 * No need for the writing half
1704 */
1705 (void)close(fds[1]);
1706
1707 savederr = 0;
1708 Buf_Init(&buf, 0);
1709
1710 do {
1711 char result[BUFSIZ];
1712 bytes_read = read(fds[0], result, sizeof(result));
1713 if (bytes_read > 0)
1714 Buf_AddBytes(&buf, result, (size_t)bytes_read);
1715 }
1716 while (bytes_read > 0 || (bytes_read == -1 && errno == EINTR));
1717 if (bytes_read == -1)
1718 savederr = errno;
1719
1720 /*
1721 * Close the input side of the pipe.
1722 */
1723 (void)close(fds[0]);
1724
1725 /*
1726 * Wait for the process to exit.
1727 */
1728 while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) {
1729 JobReapChild(pid, status, FALSE);
1730 continue;
1731 }
1732 res_len = Buf_Len(&buf);
1733 res = Buf_Destroy(&buf, FALSE);
1734
1735 if (savederr != 0)
1736 *errfmt = "Couldn't read shell's output for \"%s\"";
1737
1738 if (WIFSIGNALED(status))
1739 *errfmt = "\"%s\" exited on a signal";
1740 else if (WEXITSTATUS(status) != 0)
1741 *errfmt = "\"%s\" returned non-zero status";
1742
1743 /* Convert newlines to spaces. A final newline is just stripped */
1744 if (res_len > 0 && res[res_len - 1] == '\n')
1745 res[res_len - 1] = '\0';
1746 for (cp = res; *cp != '\0'; cp++)
1747 if (*cp == '\n')
1748 *cp = ' ';
1749 break;
1750 }
1751 return res;
1752 bad:
1753 return bmake_strdup("");
1754 }
1755
1756 /* Print a printf-style error message.
1757 *
1758 * This error message has no consequences, in particular it does not affect
1759 * the exit status. */
1760 void
1761 Error(const char *fmt, ...)
1762 {
1763 va_list ap;
1764 FILE *err_file;
1765
1766 err_file = debug_file;
1767 if (err_file == stdout)
1768 err_file = stderr;
1769 (void)fflush(stdout);
1770 for (;;) {
1771 va_start(ap, fmt);
1772 fprintf(err_file, "%s: ", progname);
1773 (void)vfprintf(err_file, fmt, ap);
1774 va_end(ap);
1775 (void)fprintf(err_file, "\n");
1776 (void)fflush(err_file);
1777 if (err_file == stderr)
1778 break;
1779 err_file = stderr;
1780 }
1781 }
1782
1783 /* Produce a Fatal error message, then exit immediately.
1784 *
1785 * If jobs are running, waits for them to finish. */
1786 void
1787 Fatal(const char *fmt, ...)
1788 {
1789 va_list ap;
1790
1791 va_start(ap, fmt);
1792 if (jobsRunning)
1793 Job_Wait();
1794
1795 (void)fflush(stdout);
1796 (void)vfprintf(stderr, fmt, ap);
1797 va_end(ap);
1798 (void)fprintf(stderr, "\n");
1799 (void)fflush(stderr);
1800
1801 PrintOnError(NULL, NULL);
1802
1803 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1804 Targ_PrintGraph(2);
1805 Trace_Log(MAKEERROR, 0);
1806 exit(2); /* Not 1 so -q can distinguish error */
1807 }
1808
1809 /*
1810 * Punt --
1811 * Major exception once jobs are being created. Kills all jobs, prints
1812 * a message and exits.
1813 *
1814 * Results:
1815 * None
1816 *
1817 * Side Effects:
1818 * All children are killed indiscriminately and the program Lib_Exits
1819 */
1820 void
1821 Punt(const char *fmt, ...)
1822 {
1823 va_list ap;
1824
1825 va_start(ap, fmt);
1826 (void)fflush(stdout);
1827 (void)fprintf(stderr, "%s: ", progname);
1828 (void)vfprintf(stderr, fmt, ap);
1829 va_end(ap);
1830 (void)fprintf(stderr, "\n");
1831 (void)fflush(stderr);
1832
1833 PrintOnError(NULL, NULL);
1834
1835 DieHorribly();
1836 }
1837
1838 /*-
1839 * DieHorribly --
1840 * Exit without giving a message.
1841 *
1842 * Results:
1843 * None
1844 *
1845 * Side Effects:
1846 * A big one...
1847 */
1848 void
1849 DieHorribly(void)
1850 {
1851 if (jobsRunning)
1852 Job_AbortAll();
1853 if (DEBUG(GRAPH2))
1854 Targ_PrintGraph(2);
1855 Trace_Log(MAKEERROR, 0);
1856 exit(2); /* Not 1, so -q can distinguish error */
1857 }
1858
1859 /*
1860 * Finish --
1861 * Called when aborting due to errors in child shell to signal
1862 * abnormal exit.
1863 *
1864 * Results:
1865 * None
1866 *
1867 * Side Effects:
1868 * The program exits
1869 */
1870 void
1871 Finish(int errors)
1872 /* number of errors encountered in Make_Make */
1873 {
1874 if (dieQuietly(NULL, -1))
1875 exit(2);
1876 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1877 }
1878
1879 /*
1880 * eunlink --
1881 * Remove a file carefully, avoiding directories.
1882 */
1883 int
1884 eunlink(const char *file)
1885 {
1886 struct stat st;
1887
1888 if (lstat(file, &st) == -1)
1889 return -1;
1890
1891 if (S_ISDIR(st.st_mode)) {
1892 errno = EISDIR;
1893 return -1;
1894 }
1895 return unlink(file);
1896 }
1897
1898 static void
1899 write_all(int fd, const void *data, size_t n)
1900 {
1901 const char *mem = data;
1902
1903 while (n > 0) {
1904 ssize_t written = write(fd, mem, n);
1905 if (written == -1 && errno == EAGAIN)
1906 continue;
1907 if (written == -1)
1908 break;
1909 mem += written;
1910 n -= (size_t)written;
1911 }
1912 }
1913
1914 /*
1915 * execDie --
1916 * Print why exec failed, avoiding stdio.
1917 */
1918 void MAKE_ATTR_DEAD
1919 execDie(const char *af, const char *av)
1920 {
1921 Buffer buf;
1922
1923 Buf_Init(&buf, 0);
1924 Buf_AddStr(&buf, progname);
1925 Buf_AddStr(&buf, ": ");
1926 Buf_AddStr(&buf, af);
1927 Buf_AddStr(&buf, "(");
1928 Buf_AddStr(&buf, av);
1929 Buf_AddStr(&buf, ") failed (");
1930 Buf_AddStr(&buf, strerror(errno));
1931 Buf_AddStr(&buf, ")\n");
1932
1933 write_all(STDERR_FILENO, Buf_GetAll(&buf, NULL), Buf_Len(&buf));
1934
1935 Buf_Destroy(&buf, TRUE);
1936 _exit(1);
1937 }
1938
1939 /*
1940 * usage --
1941 * exit with usage message
1942 */
1943 static void
1944 usage(void)
1945 {
1946 char *p;
1947 if ((p = strchr(progname, '[')) != NULL)
1948 *p = '\0';
1949
1950 (void)fprintf(stderr,
1951 "usage: %s [-BeikNnqrstWwX] \n"
1952 " [-C directory] [-D variable] [-d flags] [-f makefile]\n"
1953 " [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n"
1954 " [-V variable] [-v variable] [variable=value] [target ...]\n",
1955 progname);
1956 exit(2);
1957 }
1958
1959 /*
1960 * realpath(3) can get expensive, cache results...
1961 */
1962 static GNode *cached_realpaths = NULL;
1963
1964 static GNode *
1965 get_cached_realpaths(void)
1966 {
1967
1968 if (!cached_realpaths) {
1969 cached_realpaths = Targ_NewGN("Realpath");
1970 #ifndef DEBUG_REALPATH_CACHE
1971 cached_realpaths->flags = INTERNAL;
1972 #endif
1973 }
1974
1975 return cached_realpaths;
1976 }
1977
1978 /* purge any relative paths */
1979 static void
1980 purge_cached_realpaths(void)
1981 {
1982 GNode *cache = get_cached_realpaths();
1983 HashEntry *he, *nhe;
1984 HashIter hi;
1985
1986 HashIter_Init(&hi, &cache->context);
1987 he = HashIter_Next(&hi);
1988 while (he != NULL) {
1989 nhe = HashIter_Next(&hi);
1990 if (he->key[0] != '/') {
1991 if (DEBUG(DIR))
1992 fprintf(stderr, "cached_realpath: purging %s\n", he->key);
1993 Hash_DeleteEntry(&cache->context, he);
1994 }
1995 he = nhe;
1996 }
1997 }
1998
1999 char *
2000 cached_realpath(const char *pathname, char *resolved)
2001 {
2002 GNode *cache;
2003 const char *rp;
2004 char *cp;
2005
2006 if (!pathname || !pathname[0])
2007 return NULL;
2008
2009 cache = get_cached_realpaths();
2010
2011 if ((rp = Var_Value(pathname, cache, &cp)) != NULL) {
2012 /* a hit */
2013 strncpy(resolved, rp, MAXPATHLEN);
2014 resolved[MAXPATHLEN - 1] = '\0';
2015 } else if ((rp = realpath(pathname, resolved)) != NULL) {
2016 Var_Set(pathname, rp, cache);
2017 } /* else should we negative-cache? */
2018
2019 bmake_free(cp);
2020 return rp ? resolved : NULL;
2021 }
2022
2023
2024 static int
2025 addErrorCMD(void *cmdp, void *gnp)
2026 {
2027 if (cmdp == NULL)
2028 return 1; /* stop */
2029 Var_Append(".ERROR_CMD", cmdp, VAR_GLOBAL);
2030 return 0;
2031 }
2032
2033 /*
2034 * Return true if we should die without noise.
2035 * For example our failing child was a sub-make
2036 * or failure happend elsewhere.
2037 */
2038 int
2039 dieQuietly(GNode *gn, int bf)
2040 {
2041 static int quietly = -1;
2042
2043 if (quietly < 0) {
2044 if (DEBUG(JOB) || getBoolean(".MAKE.DIE_QUIETLY", 1) == 0)
2045 quietly = 0;
2046 else if (bf >= 0)
2047 quietly = bf;
2048 else
2049 quietly = gn != NULL ? ((gn->type & (OP_MAKE)) != 0) : 0;
2050 }
2051 return quietly;
2052 }
2053
2054 void
2055 PrintOnError(GNode *gn, const char *s)
2056 {
2057 static GNode *en = NULL;
2058 const char *expr;
2059 char *cp;
2060
2061 if (DEBUG(HASH)) {
2062 Targ_Stats();
2063 Var_Stats();
2064 }
2065
2066 /* we generally want to keep quiet if a sub-make died */
2067 if (dieQuietly(gn, -1))
2068 return;
2069
2070 if (s)
2071 printf("%s", s);
2072
2073 printf("\n%s: stopped in %s\n", progname, curdir);
2074
2075 if (en)
2076 return; /* we've been here! */
2077 if (gn) {
2078 /*
2079 * We can print this even if there is no .ERROR target.
2080 */
2081 Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL);
2082 Var_Delete(".ERROR_CMD", VAR_GLOBAL);
2083 Lst_ForEachUntil(gn->commands, addErrorCMD, gn);
2084 }
2085 expr = "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}";
2086 (void)Var_Subst(expr, VAR_GLOBAL, VARE_WANTRES, &cp);
2087 /* TODO: handle errors */
2088 printf("%s", cp);
2089 free(cp);
2090 fflush(stdout);
2091
2092 /*
2093 * Finally, see if there is a .ERROR target, and run it if so.
2094 */
2095 en = Targ_FindNode(".ERROR");
2096 if (en) {
2097 en->type |= OP_SPECIAL;
2098 Compat_Make(en, en);
2099 }
2100 }
2101
2102 void
2103 Main_ExportMAKEFLAGS(Boolean first)
2104 {
2105 static Boolean once = TRUE;
2106 const char *expr;
2107 char *s;
2108
2109 if (once != first)
2110 return;
2111 once = FALSE;
2112
2113 expr = "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}";
2114 (void)Var_Subst(expr, VAR_CMD, VARE_WANTRES, &s);
2115 /* TODO: handle errors */
2116 if (s[0] != '\0') {
2117 #ifdef POSIX
2118 setenv("MAKEFLAGS", s, 1);
2119 #else
2120 setenv("MAKE", s, 1);
2121 #endif
2122 }
2123 }
2124
2125 char *
2126 getTmpdir(void)
2127 {
2128 static char *tmpdir = NULL;
2129
2130 if (!tmpdir) {
2131 struct stat st;
2132
2133 /*
2134 * Honor $TMPDIR but only if it is valid.
2135 * Ensure it ends with /.
2136 */
2137 (void)Var_Subst("${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL,
2138 VARE_WANTRES, &tmpdir);
2139 /* TODO: handle errors */
2140 if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
2141 free(tmpdir);
2142 tmpdir = bmake_strdup(_PATH_TMP);
2143 }
2144 }
2145 return tmpdir;
2146 }
2147
2148 /*
2149 * Create and open a temp file using "pattern".
2150 * If "fnamep" is provided set it to a copy of the filename created.
2151 * Otherwise unlink the file once open.
2152 */
2153 int
2154 mkTempFile(const char *pattern, char **fnamep)
2155 {
2156 static char *tmpdir = NULL;
2157 char tfile[MAXPATHLEN];
2158 int fd;
2159
2160 if (!pattern)
2161 pattern = TMPPAT;
2162 if (!tmpdir)
2163 tmpdir = getTmpdir();
2164 if (pattern[0] == '/') {
2165 snprintf(tfile, sizeof(tfile), "%s", pattern);
2166 } else {
2167 snprintf(tfile, sizeof(tfile), "%s%s", tmpdir, pattern);
2168 }
2169 if ((fd = mkstemp(tfile)) < 0)
2170 Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
2171 if (fnamep) {
2172 *fnamep = bmake_strdup(tfile);
2173 } else {
2174 unlink(tfile); /* we just want the descriptor */
2175 }
2176 return fd;
2177 }
2178
2179 /*
2180 * Convert a string representation of a boolean.
2181 * Anything that looks like "No", "False", "Off", "0" etc,
2182 * is FALSE, otherwise TRUE.
2183 */
2184 Boolean
2185 s2Boolean(const char *s, Boolean bf)
2186 {
2187 if (s) {
2188 switch(*s) {
2189 case '\0': /* not set - the default wins */
2190 break;
2191 case '0':
2192 case 'F':
2193 case 'f':
2194 case 'N':
2195 case 'n':
2196 bf = FALSE;
2197 break;
2198 case 'O':
2199 case 'o':
2200 switch (s[1]) {
2201 case 'F':
2202 case 'f':
2203 bf = FALSE;
2204 break;
2205 default:
2206 bf = TRUE;
2207 break;
2208 }
2209 break;
2210 default:
2211 bf = TRUE;
2212 break;
2213 }
2214 }
2215 return bf;
2216 }
2217
2218 /*
2219 * Return a Boolean based on setting of a knob.
2220 *
2221 * If the knob is not set, the supplied default is the return value.
2222 * If set, anything that looks or smells like "No", "False", "Off", "0" etc,
2223 * is FALSE, otherwise TRUE.
2224 */
2225 Boolean
2226 getBoolean(const char *name, Boolean fallback)
2227 {
2228 char *expr = str_concat3("${", name, ":U:tl}");
2229 char *value;
2230 Boolean res;
2231
2232 (void)Var_Subst(expr, VAR_GLOBAL, VARE_WANTRES, &value);
2233 /* TODO: handle errors */
2234 res = s2Boolean(value, fallback);
2235 free(value);
2236 free(expr);
2237 return res;
2238 }
2239