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