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