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