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