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