main.c revision 1.443 1 /* $NetBSD: main.c,v 1.443 2020/11/08 02:56:43 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.443 2020/11/08 02:56:43 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 ReadAllMakefiles(StringList *makefiles)
1279 {
1280 StringListNode *ln;
1281
1282 for (ln = makefiles->first; ln != NULL; ln = ln->next) {
1283 const char *fname = ln->datum;
1284 if (ReadMakefile(fname) != 0)
1285 Fatal("%s: cannot open %s.", progname, fname);
1286 }
1287 }
1288
1289 static void
1290 ReadFirstDefaultMakefile(void)
1291 {
1292 char *prefs;
1293 (void)Var_Subst("${" MAKE_MAKEFILE_PREFERENCE "}",
1294 VAR_CMDLINE, VARE_WANTRES, &prefs);
1295 /* TODO: handle errors */
1296
1297 /* XXX: This should use a local list instead of opts.makefiles
1298 * since these makefiles do not come from the command line. They
1299 * also have different semantics in that only the first file that
1300 * is found is processed. See ReadAllMakefiles. */
1301 (void)str2Lst_Append(opts.makefiles, prefs, NULL);
1302 (void)Lst_ForEachUntil(opts.makefiles, ReadMakefileSucceeded, NULL);
1303 free(prefs);
1304 }
1305
1306 static void
1307 CleanUp(void)
1308 {
1309 #ifdef CLEANUP
1310 Lst_Destroy(opts.variables, free);
1311 Lst_Free(opts.makefiles); /* don't free, may be used in GNodes */
1312 Lst_Destroy(opts.create, free);
1313 #endif
1314
1315 /* print the graph now it's been processed if the user requested it */
1316 if (DEBUG(GRAPH2))
1317 Targ_PrintGraph(2);
1318
1319 Trace_Log(MAKEEND, NULL);
1320
1321 if (enterFlagObj)
1322 printf("%s: Leaving directory `%s'\n", progname, objdir);
1323 if (opts.enterFlag)
1324 printf("%s: Leaving directory `%s'\n", progname, curdir);
1325
1326 #ifdef USE_META
1327 meta_finish();
1328 #endif
1329 Suff_End();
1330 Targ_End();
1331 Arch_End();
1332 Var_End();
1333 Parse_End();
1334 Dir_End();
1335 Job_End();
1336 Trace_End();
1337 }
1338
1339 /*-
1340 * main --
1341 * The main function, for obvious reasons. Initializes variables
1342 * and a few modules, then parses the arguments give it in the
1343 * environment and on the command line. Reads the system makefile
1344 * followed by either Makefile, makefile or the file given by the
1345 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
1346 * flags it has received by then uses either the Make or the Compat
1347 * module to create the initial list of targets.
1348 *
1349 * Results:
1350 * If -q was given, exits -1 if anything was out-of-date. Else it exits
1351 * 0.
1352 *
1353 * Side Effects:
1354 * The program exits when done. Targets are created. etc. etc. etc.
1355 */
1356 int
1357 main(int argc, char **argv)
1358 {
1359 Boolean outOfDate; /* FALSE if all targets up to date */
1360 struct stat sa;
1361 const char *machine;
1362 const char *machine_arch;
1363 char *syspath = getenv("MAKESYSPATH");
1364 struct utsname utsname;
1365
1366 /* default to writing debug to stderr */
1367 opts.debug_file = stderr;
1368
1369 #ifdef SIGINFO
1370 (void)bmake_signal(SIGINFO, siginfo);
1371 #endif
1372
1373 InitRandom();
1374
1375 if ((progname = strrchr(argv[0], '/')) != NULL)
1376 progname++;
1377 else
1378 progname = argv[0];
1379
1380 UnlimitFiles();
1381
1382 if (uname(&utsname) == -1) {
1383 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
1384 strerror(errno));
1385 exit(2);
1386 }
1387
1388 /*
1389 * Get the name of this type of MACHINE from utsname
1390 * so we can share an executable for similar machines.
1391 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
1392 *
1393 * Note that both MACHINE and MACHINE_ARCH are decided at
1394 * run-time.
1395 */
1396 machine = init_machine(&utsname);
1397 machine_arch = init_machine_arch();
1398
1399 myPid = getpid(); /* remember this for vFork() */
1400
1401 /*
1402 * Just in case MAKEOBJDIR wants us to do something tricky.
1403 */
1404 Var_Init(); /* Initialize the lists of variables for
1405 * parsing arguments */
1406 Var_Set(".MAKE.OS", utsname.sysname, VAR_GLOBAL);
1407 Var_Set("MACHINE", machine, VAR_GLOBAL);
1408 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
1409 #ifdef MAKE_VERSION
1410 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
1411 #endif
1412 Var_Set(".newline", "\n", VAR_GLOBAL); /* handy for :@ loops */
1413 /*
1414 * This is the traditional preference for makefiles.
1415 */
1416 #ifndef MAKEFILE_PREFERENCE_LIST
1417 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
1418 #endif
1419 Var_Set(MAKE_MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST,
1420 VAR_GLOBAL);
1421 Var_Set(MAKE_DEPENDFILE, ".depend", VAR_GLOBAL);
1422
1423 CmdOpts_Init();
1424 allPrecious = FALSE; /* Remove targets when interrupted */
1425 deleteOnError = FALSE; /* Historical default behavior */
1426 jobsRunning = FALSE;
1427
1428 maxJobTokens = opts.maxJobs;
1429 ignorePWD = FALSE;
1430
1431 /*
1432 * Initialize the parsing, directory and variable modules to prepare
1433 * for the reading of inclusion paths and variable settings on the
1434 * command line
1435 */
1436
1437 /*
1438 * Initialize various variables.
1439 * MAKE also gets this name, for compatibility
1440 * .MAKEFLAGS gets set to the empty string just in case.
1441 * MFLAGS also gets initialized empty, for compatibility.
1442 */
1443 Parse_Init();
1444 InitVarMake(argv[0]);
1445 Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
1446 Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL);
1447 Var_Set("MFLAGS", "", VAR_GLOBAL);
1448 Var_Set(".ALLTARGETS", "", VAR_GLOBAL);
1449 /* some makefiles need to know this */
1450 Var_Set(MAKE_LEVEL ".ENV", MAKE_LEVEL_ENV, VAR_CMDLINE);
1451
1452 /*
1453 * Set some other useful macros
1454 */
1455 {
1456 char tmp[64], *ep = getenv(MAKE_LEVEL_ENV);
1457
1458 makelevel = ep != NULL && ep[0] != '\0' ? atoi(ep) : 0;
1459 if (makelevel < 0)
1460 makelevel = 0;
1461 snprintf(tmp, sizeof tmp, "%d", makelevel);
1462 Var_Set(MAKE_LEVEL, tmp, VAR_GLOBAL);
1463 snprintf(tmp, sizeof tmp, "%u", myPid);
1464 Var_Set(".MAKE.PID", tmp, VAR_GLOBAL);
1465 snprintf(tmp, sizeof tmp, "%u", getppid());
1466 Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL);
1467 }
1468 if (makelevel > 0) {
1469 char pn[1024];
1470 snprintf(pn, sizeof pn, "%s[%d]", progname, makelevel);
1471 progname = bmake_strdup(pn);
1472 }
1473
1474 #ifdef USE_META
1475 meta_init();
1476 #endif
1477 Dir_Init();
1478
1479 /*
1480 * First snag any flags out of the MAKE environment variable.
1481 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
1482 * in a different format).
1483 */
1484 #ifdef POSIX
1485 {
1486 char *p1 = explode(getenv("MAKEFLAGS"));
1487 Main_ParseArgLine(p1);
1488 free(p1);
1489 }
1490 #else
1491 Main_ParseArgLine(getenv("MAKE"));
1492 #endif
1493
1494 /*
1495 * Find where we are (now).
1496 * We take care of PWD for the automounter below...
1497 */
1498 if (getcwd(curdir, MAXPATHLEN) == NULL) {
1499 (void)fprintf(stderr, "%s: getcwd: %s.\n",
1500 progname, strerror(errno));
1501 exit(2);
1502 }
1503
1504 MainParseArgs(argc, argv);
1505
1506 if (opts.enterFlag)
1507 printf("%s: Entering directory `%s'\n", progname, curdir);
1508
1509 /*
1510 * Verify that cwd is sane.
1511 */
1512 if (stat(curdir, &sa) == -1) {
1513 (void)fprintf(stderr, "%s: %s: %s.\n",
1514 progname, curdir, strerror(errno));
1515 exit(2);
1516 }
1517
1518 #ifndef NO_PWD_OVERRIDE
1519 HandlePWD(&sa);
1520 #endif
1521 Var_Set(".CURDIR", curdir, VAR_GLOBAL);
1522
1523 InitObjdir(machine, machine_arch);
1524
1525 /*
1526 * Initialize archive, target and suffix modules in preparation for
1527 * parsing the makefile(s)
1528 */
1529 Arch_Init();
1530 Targ_Init();
1531 Suff_Init();
1532 Trace_Init(tracefile);
1533
1534 DEFAULT = NULL;
1535 (void)time(&now);
1536
1537 Trace_Log(MAKESTART, NULL);
1538
1539 InitVarTargets();
1540
1541 InitDefSysIncPath(syspath);
1542
1543 /*
1544 * Read in the built-in rules first, followed by the specified
1545 * makefiles, or the default makefile and Makefile, in that order,
1546 * if no makefiles were given on the command line.
1547 */
1548 if (!opts.noBuiltins)
1549 ReadBuiltinRules();
1550 if (!Lst_IsEmpty(opts.makefiles))
1551 ReadAllMakefiles(opts.makefiles);
1552 else
1553 ReadFirstDefaultMakefile();
1554
1555 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1556 if (!opts.noBuiltins || opts.printVars == PVM_NONE) {
1557 /* ignore /dev/null and anything starting with "no" */
1558 (void)Var_Subst("${.MAKE.DEPENDFILE:N/dev/null:Nno*:T}",
1559 VAR_CMDLINE, VARE_WANTRES, &makeDependfile);
1560 if (makeDependfile[0] != '\0') {
1561 /* TODO: handle errors */
1562 doing_depend = TRUE;
1563 (void)ReadMakefile(makeDependfile);
1564 doing_depend = FALSE;
1565 }
1566 }
1567
1568 if (enterFlagObj)
1569 printf("%s: Entering directory `%s'\n", progname, objdir);
1570
1571 MakeMode(NULL);
1572
1573 {
1574 void *freeIt;
1575 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &freeIt),
1576 VAR_GLOBAL);
1577 bmake_free(freeIt);
1578
1579 }
1580
1581 InitMaxJobs();
1582
1583 /*
1584 * Be compatible if user did not specify -j and did not explicitly
1585 * turned compatibility on
1586 */
1587 if (!opts.compatMake && !forceJobs) {
1588 opts.compatMake = TRUE;
1589 }
1590
1591 if (!opts.compatMake)
1592 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1593 DEBUG5(JOB, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1594 jp_0, jp_1, opts.maxJobs, maxJobTokens, opts.compatMake ? 1 : 0);
1595
1596 if (opts.printVars == PVM_NONE)
1597 Main_ExportMAKEFLAGS(TRUE); /* initial export */
1598
1599 InitVpath();
1600
1601 /*
1602 * Now that all search paths have been read for suffixes et al, it's
1603 * time to add the default search path to their lists...
1604 */
1605 Suff_DoPaths();
1606
1607 /*
1608 * Propagate attributes through :: dependency lists.
1609 */
1610 Targ_Propagate();
1611
1612 /* print the initial graph, if the user requested it */
1613 if (DEBUG(GRAPH1))
1614 Targ_PrintGraph(1);
1615
1616 /* print the values of any variables requested by the user */
1617 if (opts.printVars != PVM_NONE) {
1618 doPrintVars();
1619 outOfDate = FALSE;
1620 } else {
1621 outOfDate = runTargets();
1622 }
1623
1624 CleanUp();
1625
1626 if (DEBUG(LINT) && (errors > 0 || Parse_GetFatals() > 0))
1627 return 2; /* Not 1 so -q can distinguish error */
1628 return outOfDate ? 1 : 0;
1629 }
1630
1631 /* Open and parse the given makefile, with all its side effects.
1632 *
1633 * Results:
1634 * 0 if ok. -1 if couldn't open file.
1635 */
1636 static int
1637 ReadMakefile(const char *fname)
1638 {
1639 int fd;
1640 char *name, *path = NULL;
1641
1642 if (!strcmp(fname, "-")) {
1643 Parse_File(NULL /*stdin*/, -1);
1644 Var_Set("MAKEFILE", "", VAR_INTERNAL);
1645 } else {
1646 /* if we've chdir'd, rebuild the path name */
1647 if (strcmp(curdir, objdir) && *fname != '/') {
1648 path = str_concat3(curdir, "/", fname);
1649 fd = open(path, O_RDONLY);
1650 if (fd != -1) {
1651 fname = path;
1652 goto found;
1653 }
1654 free(path);
1655
1656 /* If curdir failed, try objdir (ala .depend) */
1657 path = str_concat3(objdir, "/", fname);
1658 fd = open(path, O_RDONLY);
1659 if (fd != -1) {
1660 fname = path;
1661 goto found;
1662 }
1663 } else {
1664 fd = open(fname, O_RDONLY);
1665 if (fd != -1)
1666 goto found;
1667 }
1668 /* look in -I and system include directories. */
1669 name = Dir_FindFile(fname, parseIncPath);
1670 if (!name) {
1671 SearchPath *sysInc = Lst_IsEmpty(sysIncPath)
1672 ? defSysIncPath : sysIncPath;
1673 name = Dir_FindFile(fname, sysInc);
1674 }
1675 if (!name || (fd = open(name, O_RDONLY)) == -1) {
1676 free(name);
1677 free(path);
1678 return -1;
1679 }
1680 fname = name;
1681 /*
1682 * set the MAKEFILE variable desired by System V fans -- the
1683 * placement of the setting here means it gets set to the last
1684 * makefile specified, as it is set by SysV make.
1685 */
1686 found:
1687 if (!doing_depend)
1688 Var_Set("MAKEFILE", fname, VAR_INTERNAL);
1689 Parse_File(fname, fd);
1690 }
1691 free(path);
1692 return 0;
1693 }
1694
1695
1696
1697 /*-
1698 * Cmd_Exec --
1699 * Execute the command in cmd, and return the output of that command
1700 * in a string. In the output, newlines are replaced with spaces.
1701 *
1702 * Results:
1703 * A string containing the output of the command, or the empty string.
1704 * *errfmt returns a format string describing the command failure,
1705 * if any, using a single %s conversion specification.
1706 *
1707 * Side Effects:
1708 * The string must be freed by the caller.
1709 */
1710 char *
1711 Cmd_Exec(const char *cmd, const char **errfmt)
1712 {
1713 const char *args[4]; /* Args for invoking the shell */
1714 int fds[2]; /* Pipe streams */
1715 int cpid; /* Child PID */
1716 int pid; /* PID from wait() */
1717 int status; /* command exit status */
1718 Buffer buf; /* buffer to store the result */
1719 ssize_t bytes_read;
1720 char *res; /* result */
1721 size_t res_len;
1722 char *cp;
1723 int savederr; /* saved errno */
1724
1725 *errfmt = NULL;
1726
1727 if (!shellName)
1728 Shell_Init();
1729 /*
1730 * Set up arguments for shell
1731 */
1732 args[0] = shellName;
1733 args[1] = "-c";
1734 args[2] = cmd;
1735 args[3] = NULL;
1736
1737 /*
1738 * Open a pipe for fetching its output
1739 */
1740 if (pipe(fds) == -1) {
1741 *errfmt = "Couldn't create pipe for \"%s\"";
1742 goto bad;
1743 }
1744
1745 /*
1746 * Fork
1747 */
1748 switch (cpid = vFork()) {
1749 case 0:
1750 (void)close(fds[0]); /* Close input side of pipe */
1751
1752 /*
1753 * Duplicate the output stream to the shell's output, then
1754 * shut the extra thing down. Note we don't fetch the error
1755 * stream...why not? Why?
1756 */
1757 (void)dup2(fds[1], 1);
1758 (void)close(fds[1]);
1759
1760 Var_ExportVars();
1761
1762 (void)execv(shellPath, UNCONST(args));
1763 _exit(1);
1764 /*NOTREACHED*/
1765
1766 case -1:
1767 *errfmt = "Couldn't exec \"%s\"";
1768 goto bad;
1769
1770 default:
1771 (void)close(fds[1]); /* No need for the writing half */
1772
1773 savederr = 0;
1774 Buf_Init(&buf);
1775
1776 do {
1777 char result[BUFSIZ];
1778 bytes_read = read(fds[0], result, sizeof result);
1779 if (bytes_read > 0)
1780 Buf_AddBytes(&buf, result, (size_t)bytes_read);
1781 } while (bytes_read > 0 || (bytes_read == -1 && errno == EINTR));
1782 if (bytes_read == -1)
1783 savederr = errno;
1784
1785 (void)close(fds[0]); /* Close the input side of the pipe. */
1786
1787 /* Wait for the process to exit. */
1788 while((pid = waitpid(cpid, &status, 0)) != cpid && pid >= 0)
1789 JobReapChild(pid, status, FALSE);
1790
1791 res_len = Buf_Len(&buf);
1792 res = Buf_Destroy(&buf, FALSE);
1793
1794 if (savederr != 0)
1795 *errfmt = "Couldn't read shell's output for \"%s\"";
1796
1797 if (WIFSIGNALED(status))
1798 *errfmt = "\"%s\" exited on a signal";
1799 else if (WEXITSTATUS(status) != 0)
1800 *errfmt = "\"%s\" returned non-zero status";
1801
1802 /* Convert newlines to spaces. A final newline is just stripped */
1803 if (res_len > 0 && res[res_len - 1] == '\n')
1804 res[res_len - 1] = '\0';
1805 for (cp = res; *cp != '\0'; cp++)
1806 if (*cp == '\n')
1807 *cp = ' ';
1808 break;
1809 }
1810 return res;
1811 bad:
1812 return bmake_strdup("");
1813 }
1814
1815 /* Print a printf-style error message.
1816 *
1817 * In default mode, this error message has no consequences, in particular it
1818 * does not affect the exit status. Only in lint mode (-dL) it does. */
1819 void
1820 Error(const char *fmt, ...)
1821 {
1822 va_list ap;
1823 FILE *err_file;
1824
1825 err_file = opts.debug_file;
1826 if (err_file == stdout)
1827 err_file = stderr;
1828 (void)fflush(stdout);
1829 for (;;) {
1830 va_start(ap, fmt);
1831 fprintf(err_file, "%s: ", progname);
1832 (void)vfprintf(err_file, fmt, ap);
1833 va_end(ap);
1834 (void)fprintf(err_file, "\n");
1835 (void)fflush(err_file);
1836 if (err_file == stderr)
1837 break;
1838 err_file = stderr;
1839 }
1840 errors++;
1841 }
1842
1843 /* Produce a Fatal error message, then exit immediately.
1844 *
1845 * If jobs are running, wait for them to finish. */
1846 void
1847 Fatal(const char *fmt, ...)
1848 {
1849 va_list ap;
1850
1851 va_start(ap, fmt);
1852 if (jobsRunning)
1853 Job_Wait();
1854
1855 (void)fflush(stdout);
1856 (void)vfprintf(stderr, fmt, ap);
1857 va_end(ap);
1858 (void)fprintf(stderr, "\n");
1859 (void)fflush(stderr);
1860
1861 PrintOnError(NULL, NULL);
1862
1863 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1864 Targ_PrintGraph(2);
1865 Trace_Log(MAKEERROR, NULL);
1866 exit(2); /* Not 1 so -q can distinguish error */
1867 }
1868
1869 /* Major exception once jobs are being created.
1870 * Kills all jobs, prints a message and exits. */
1871 void
1872 Punt(const char *fmt, ...)
1873 {
1874 va_list ap;
1875
1876 va_start(ap, fmt);
1877 (void)fflush(stdout);
1878 (void)fprintf(stderr, "%s: ", progname);
1879 (void)vfprintf(stderr, fmt, ap);
1880 va_end(ap);
1881 (void)fprintf(stderr, "\n");
1882 (void)fflush(stderr);
1883
1884 PrintOnError(NULL, NULL);
1885
1886 DieHorribly();
1887 }
1888
1889 /* Exit without giving a message. */
1890 void
1891 DieHorribly(void)
1892 {
1893 if (jobsRunning)
1894 Job_AbortAll();
1895 if (DEBUG(GRAPH2))
1896 Targ_PrintGraph(2);
1897 Trace_Log(MAKEERROR, NULL);
1898 exit(2); /* Not 1, so -q can distinguish error */
1899 }
1900
1901 /* Called when aborting due to errors in child shell to signal abnormal exit.
1902 * The program exits.
1903 * Errors is the number of errors encountered in Make_Make. */
1904 void
1905 Finish(int errs)
1906 {
1907 if (shouldDieQuietly(NULL, -1))
1908 exit(2);
1909 Fatal("%d error%s", errs, errs == 1 ? "" : "s");
1910 }
1911
1912 /*
1913 * eunlink --
1914 * Remove a file carefully, avoiding directories.
1915 */
1916 int
1917 eunlink(const char *file)
1918 {
1919 struct stat st;
1920
1921 if (lstat(file, &st) == -1)
1922 return -1;
1923
1924 if (S_ISDIR(st.st_mode)) {
1925 errno = EISDIR;
1926 return -1;
1927 }
1928 return unlink(file);
1929 }
1930
1931 static void
1932 write_all(int fd, const void *data, size_t n)
1933 {
1934 const char *mem = data;
1935
1936 while (n > 0) {
1937 ssize_t written = write(fd, mem, n);
1938 if (written == -1 && errno == EAGAIN)
1939 continue;
1940 if (written == -1)
1941 break;
1942 mem += written;
1943 n -= (size_t)written;
1944 }
1945 }
1946
1947 /*
1948 * execDie --
1949 * Print why exec failed, avoiding stdio.
1950 */
1951 void MAKE_ATTR_DEAD
1952 execDie(const char *af, const char *av)
1953 {
1954 Buffer buf;
1955
1956 Buf_Init(&buf);
1957 Buf_AddStr(&buf, progname);
1958 Buf_AddStr(&buf, ": ");
1959 Buf_AddStr(&buf, af);
1960 Buf_AddStr(&buf, "(");
1961 Buf_AddStr(&buf, av);
1962 Buf_AddStr(&buf, ") failed (");
1963 Buf_AddStr(&buf, strerror(errno));
1964 Buf_AddStr(&buf, ")\n");
1965
1966 write_all(STDERR_FILENO, Buf_GetAll(&buf, NULL), Buf_Len(&buf));
1967
1968 Buf_Destroy(&buf, TRUE);
1969 _exit(1);
1970 }
1971
1972 /*
1973 * usage --
1974 * exit with usage message
1975 */
1976 static void
1977 usage(void)
1978 {
1979 char *p;
1980 if ((p = strchr(progname, '[')) != NULL)
1981 *p = '\0';
1982
1983 (void)fprintf(stderr,
1984 "usage: %s [-BeikNnqrstWwX] \n"
1985 " [-C directory] [-D variable] [-d flags] [-f makefile]\n"
1986 " [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n"
1987 " [-V variable] [-v variable] [variable=value] [target ...]\n",
1988 progname);
1989 exit(2);
1990 }
1991
1992 /*
1993 * realpath(3) can get expensive, cache results...
1994 */
1995 static GNode *cached_realpaths = NULL;
1996
1997 static GNode *
1998 get_cached_realpaths(void)
1999 {
2000
2001 if (!cached_realpaths) {
2002 cached_realpaths = Targ_NewGN("Realpath");
2003 #ifndef DEBUG_REALPATH_CACHE
2004 cached_realpaths->flags = INTERNAL;
2005 #endif
2006 }
2007
2008 return cached_realpaths;
2009 }
2010
2011 /* purge any relative paths */
2012 static void
2013 purge_cached_realpaths(void)
2014 {
2015 GNode *cache = get_cached_realpaths();
2016 HashEntry *he, *nhe;
2017 HashIter hi;
2018
2019 HashIter_Init(&hi, &cache->context);
2020 he = HashIter_Next(&hi);
2021 while (he != NULL) {
2022 nhe = HashIter_Next(&hi);
2023 if (he->key[0] != '/') {
2024 if (DEBUG(DIR))
2025 fprintf(stderr, "cached_realpath: purging %s\n", he->key);
2026 HashTable_DeleteEntry(&cache->context, he);
2027 }
2028 he = nhe;
2029 }
2030 }
2031
2032 char *
2033 cached_realpath(const char *pathname, char *resolved)
2034 {
2035 GNode *cache;
2036 const char *rp;
2037 void *freeIt;
2038
2039 if (pathname == NULL || pathname[0] == '\0')
2040 return NULL;
2041
2042 cache = get_cached_realpaths();
2043
2044 if ((rp = Var_Value(pathname, cache, &freeIt)) != NULL) {
2045 /* a hit */
2046 strncpy(resolved, rp, MAXPATHLEN);
2047 resolved[MAXPATHLEN - 1] = '\0';
2048 } else if ((rp = realpath(pathname, resolved)) != NULL) {
2049 Var_Set(pathname, rp, cache);
2050 } /* else should we negative-cache? */
2051
2052 bmake_free(freeIt);
2053 return rp ? resolved : NULL;
2054 }
2055
2056 /*
2057 * Return true if we should die without noise.
2058 * For example our failing child was a sub-make or failure happened elsewhere.
2059 */
2060 Boolean
2061 shouldDieQuietly(GNode *gn, int bf)
2062 {
2063 static int quietly = -1;
2064
2065 if (quietly < 0) {
2066 if (DEBUG(JOB) || !GetBooleanVar(".MAKE.DIE_QUIETLY", TRUE))
2067 quietly = 0;
2068 else if (bf >= 0)
2069 quietly = bf;
2070 else
2071 quietly = gn != NULL && (gn->type & OP_MAKE);
2072 }
2073 return quietly;
2074 }
2075
2076 static void
2077 SetErrorVars(GNode *gn)
2078 {
2079 StringListNode *ln;
2080
2081 /*
2082 * We can print this even if there is no .ERROR target.
2083 */
2084 Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL);
2085 Var_Delete(".ERROR_CMD", VAR_GLOBAL);
2086
2087 for (ln = gn->commands->first; ln != NULL; ln = ln->next) {
2088 const char *cmd = ln->datum;
2089
2090 if (cmd == NULL)
2091 break;
2092 Var_Append(".ERROR_CMD", cmd, VAR_GLOBAL);
2093 }
2094 }
2095
2096 void
2097 PrintOnError(GNode *gn, const char *s)
2098 {
2099 static GNode *en = NULL;
2100 const char *expr;
2101 char *cp;
2102
2103 if (DEBUG(HASH)) {
2104 Targ_Stats();
2105 Var_Stats();
2106 }
2107
2108 /* we generally want to keep quiet if a sub-make died */
2109 if (shouldDieQuietly(gn, -1))
2110 return;
2111
2112 if (s)
2113 printf("%s", s);
2114
2115 printf("\n%s: stopped in %s\n", progname, curdir);
2116
2117 if (en)
2118 return; /* we've been here! */
2119 if (gn)
2120 SetErrorVars(gn);
2121 expr = "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}";
2122 (void)Var_Subst(expr, VAR_GLOBAL, VARE_WANTRES, &cp);
2123 /* TODO: handle errors */
2124 printf("%s", cp);
2125 free(cp);
2126 fflush(stdout);
2127
2128 /*
2129 * Finally, see if there is a .ERROR target, and run it if so.
2130 */
2131 en = Targ_FindNode(".ERROR");
2132 if (en) {
2133 en->type |= OP_SPECIAL;
2134 Compat_Make(en, en);
2135 }
2136 }
2137
2138 void
2139 Main_ExportMAKEFLAGS(Boolean first)
2140 {
2141 static Boolean once = TRUE;
2142 const char *expr;
2143 char *s;
2144
2145 if (once != first)
2146 return;
2147 once = FALSE;
2148
2149 expr = "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}";
2150 (void)Var_Subst(expr, VAR_CMDLINE, VARE_WANTRES, &s);
2151 /* TODO: handle errors */
2152 if (s[0] != '\0') {
2153 #ifdef POSIX
2154 setenv("MAKEFLAGS", s, 1);
2155 #else
2156 setenv("MAKE", s, 1);
2157 #endif
2158 }
2159 }
2160
2161 char *
2162 getTmpdir(void)
2163 {
2164 static char *tmpdir = NULL;
2165
2166 if (!tmpdir) {
2167 struct stat st;
2168
2169 /*
2170 * Honor $TMPDIR but only if it is valid.
2171 * Ensure it ends with /.
2172 */
2173 (void)Var_Subst("${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL,
2174 VARE_WANTRES, &tmpdir);
2175 /* TODO: handle errors */
2176 if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
2177 free(tmpdir);
2178 tmpdir = bmake_strdup(_PATH_TMP);
2179 }
2180 }
2181 return tmpdir;
2182 }
2183
2184 /*
2185 * Create and open a temp file using "pattern".
2186 * If out_fname is provided, set it to a copy of the filename created.
2187 * Otherwise unlink the file once open.
2188 */
2189 int
2190 mkTempFile(const char *pattern, char **out_fname)
2191 {
2192 static char *tmpdir = NULL;
2193 char tfile[MAXPATHLEN];
2194 int fd;
2195
2196 if (pattern == NULL)
2197 pattern = TMPPAT;
2198 if (tmpdir == NULL)
2199 tmpdir = getTmpdir();
2200 if (pattern[0] == '/') {
2201 snprintf(tfile, sizeof tfile, "%s", pattern);
2202 } else {
2203 snprintf(tfile, sizeof tfile, "%s%s", tmpdir, pattern);
2204 }
2205 if ((fd = mkstemp(tfile)) < 0)
2206 Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
2207 if (out_fname) {
2208 *out_fname = bmake_strdup(tfile);
2209 } else {
2210 unlink(tfile); /* we just want the descriptor */
2211 }
2212 return fd;
2213 }
2214
2215 /*
2216 * Convert a string representation of a boolean.
2217 * Anything that looks like "No", "False", "Off", "0" etc,
2218 * is FALSE, otherwise TRUE.
2219 */
2220 Boolean
2221 ParseBoolean(const char *s, Boolean bf)
2222 {
2223 switch(s[0]) {
2224 case '\0': /* not set - the default wins */
2225 break;
2226 case '0':
2227 case 'F':
2228 case 'f':
2229 case 'N':
2230 case 'n':
2231 return FALSE;
2232 case 'O':
2233 case 'o':
2234 return s[1] != 'F' && s[1] != 'f';
2235 default:
2236 return TRUE;
2237 }
2238 return bf;
2239 }
2240