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