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