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