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