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