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