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