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