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