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