main.c revision 1.556 1 /* $NetBSD: main.c,v 1.556 2021/12/27 23:06:19 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.556 2021/12/27 23:06:19 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 /*
1222 * Free the list nodes but not the actual filenames since these may
1223 * still be used in GNodes.
1224 *
1225 * TODO: Check whether the above is still true after Str_Intern has
1226 * been added.
1227 */
1228 Lst_Done(&sysMkFiles);
1229 }
1230
1231 static void
1232 InitMaxJobs(void)
1233 {
1234 char *value;
1235 int n;
1236
1237 if (forceJobs || opts.compatMake ||
1238 !Var_Exists(SCOPE_GLOBAL, ".MAKE.JOBS"))
1239 return;
1240
1241 (void)Var_Subst("${.MAKE.JOBS}", SCOPE_GLOBAL, VARE_WANTRES, &value);
1242 /* TODO: handle errors */
1243 n = (int)strtol(value, NULL, 0);
1244 if (n < 1) {
1245 (void)fprintf(stderr,
1246 "%s: illegal value for .MAKE.JOBS "
1247 "-- must be positive integer!\n",
1248 progname);
1249 exit(2); /* Not 1 so -q can distinguish error */
1250 }
1251
1252 if (n != opts.maxJobs) {
1253 Global_Append(MAKEFLAGS, "-j");
1254 Global_Append(MAKEFLAGS, value);
1255 }
1256
1257 opts.maxJobs = n;
1258 maxJobTokens = opts.maxJobs;
1259 forceJobs = true;
1260 free(value);
1261 }
1262
1263 /*
1264 * For compatibility, look at the directories in the VPATH variable
1265 * and add them to the search path, if the variable is defined. The
1266 * variable's value is in the same format as the PATH environment
1267 * variable, i.e. <directory>:<directory>:<directory>...
1268 */
1269 static void
1270 InitVpath(void)
1271 {
1272 char *vpath, savec, *path;
1273 if (!Var_Exists(SCOPE_CMDLINE, "VPATH"))
1274 return;
1275
1276 (void)Var_Subst("${VPATH}", SCOPE_CMDLINE, VARE_WANTRES, &vpath);
1277 /* TODO: handle errors */
1278 path = vpath;
1279 do {
1280 char *cp;
1281 /* skip to end of directory */
1282 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1283 continue;
1284 /* Save terminator character so know when to stop */
1285 savec = *cp;
1286 *cp = '\0';
1287 /* Add directory to search path */
1288 (void)SearchPath_Add(&dirSearchPath, path);
1289 *cp = savec;
1290 path = cp + 1;
1291 } while (savec == ':');
1292 free(vpath);
1293 }
1294
1295 static void
1296 ReadAllMakefiles(const StringList *makefiles)
1297 {
1298 StringListNode *ln;
1299
1300 for (ln = makefiles->first; ln != NULL; ln = ln->next) {
1301 const char *fname = ln->datum;
1302 if (!ReadMakefile(fname))
1303 Fatal("%s: cannot open %s.", progname, fname);
1304 }
1305 }
1306
1307 static void
1308 ReadFirstDefaultMakefile(void)
1309 {
1310 StringListNode *ln;
1311 char *prefs;
1312
1313 (void)Var_Subst("${" MAKE_MAKEFILE_PREFERENCE "}",
1314 SCOPE_CMDLINE, VARE_WANTRES, &prefs);
1315 /* TODO: handle errors */
1316
1317 /*
1318 * XXX: This should use a local list instead of opts.makefiles since
1319 * these makefiles do not come from the command line. They also have
1320 * different semantics in that only the first file that is found is
1321 * processed. See ReadAllMakefiles.
1322 */
1323 (void)str2Lst_Append(&opts.makefiles, prefs);
1324
1325 for (ln = opts.makefiles.first; ln != NULL; ln = ln->next)
1326 if (ReadMakefile(ln->datum))
1327 break;
1328
1329 free(prefs);
1330 }
1331
1332 /*
1333 * Initialize variables such as MAKE, MACHINE, .MAKEFLAGS.
1334 * Initialize a few modules.
1335 * Parse the arguments from MAKEFLAGS and the command line.
1336 */
1337 static void
1338 main_Init(int argc, char **argv)
1339 {
1340 struct stat sa;
1341 const char *machine;
1342 const char *machine_arch;
1343 char *syspath = getenv("MAKESYSPATH");
1344 struct utsname utsname;
1345
1346 /* default to writing debug to stderr */
1347 opts.debug_file = stderr;
1348
1349 Str_Intern_Init();
1350 HashTable_Init(&cached_realpaths);
1351
1352 #ifdef SIGINFO
1353 (void)bmake_signal(SIGINFO, siginfo);
1354 #endif
1355
1356 InitRandom();
1357
1358 progname = str_basename(argv[0]);
1359
1360 UnlimitFiles();
1361
1362 if (uname(&utsname) == -1) {
1363 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
1364 strerror(errno));
1365 exit(2);
1366 }
1367
1368 /*
1369 * Get the name of this type of MACHINE from utsname
1370 * so we can share an executable for similar machines.
1371 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
1372 *
1373 * Note that both MACHINE and MACHINE_ARCH are decided at
1374 * run-time.
1375 */
1376 machine = InitVarMachine(&utsname);
1377 machine_arch = InitVarMachineArch();
1378
1379 myPid = getpid(); /* remember this for vFork() */
1380
1381 /*
1382 * Just in case MAKEOBJDIR wants us to do something tricky.
1383 */
1384 Targ_Init();
1385 Var_Init();
1386 Global_Set(".MAKE.OS", utsname.sysname);
1387 Global_Set("MACHINE", machine);
1388 Global_Set("MACHINE_ARCH", machine_arch);
1389 #ifdef MAKE_VERSION
1390 Global_Set("MAKE_VERSION", MAKE_VERSION);
1391 #endif
1392 Global_Set(".newline", "\n"); /* handy for :@ loops */
1393 #ifndef MAKEFILE_PREFERENCE_LIST
1394 /* This is the traditional preference for makefiles. */
1395 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
1396 #endif
1397 Global_Set(MAKE_MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST);
1398 Global_Set(MAKE_DEPENDFILE, ".depend");
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 Global_Set(MAKEFLAGS, "");
1423 Global_Set(MAKEOVERRIDES, "");
1424 Global_Set("MFLAGS", "");
1425 Global_Set(".ALLTARGETS", "");
1426 Var_Set(SCOPE_CMDLINE, MAKE_LEVEL ".ENV", MAKE_LEVEL_ENV);
1427
1428 /* Set some other useful variables. */
1429 {
1430 char buf[64], *ep = getenv(MAKE_LEVEL_ENV);
1431
1432 makelevel = ep != NULL && ep[0] != '\0' ? atoi(ep) : 0;
1433 if (makelevel < 0)
1434 makelevel = 0;
1435 snprintf(buf, sizeof buf, "%d", makelevel);
1436 Global_Set(MAKE_LEVEL, buf);
1437 snprintf(buf, sizeof buf, "%u", myPid);
1438 Global_Set(".MAKE.PID", buf);
1439 snprintf(buf, sizeof buf, "%u", getppid());
1440 Global_Set(".MAKE.PPID", buf);
1441 snprintf(buf, sizeof buf, "%u", getuid());
1442 Global_Set(".MAKE.UID", buf);
1443 snprintf(buf, sizeof buf, "%u", getgid());
1444 Global_Set(".MAKE.GID", buf);
1445 }
1446 if (makelevel > 0) {
1447 char pn[1024];
1448 snprintf(pn, sizeof pn, "%s[%d]", progname, makelevel);
1449 progname = bmake_strdup(pn);
1450 }
1451
1452 #ifdef USE_META
1453 meta_init();
1454 #endif
1455 Dir_Init();
1456
1457 #ifdef POSIX
1458 {
1459 char *p1 = explode(getenv("MAKEFLAGS"));
1460 Main_ParseArgLine(p1);
1461 free(p1);
1462 }
1463 #else
1464 /*
1465 * First snag any flags out of the MAKE environment variable.
1466 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
1467 * in a different format).
1468 */
1469 Main_ParseArgLine(getenv("MAKE"));
1470 #endif
1471
1472 if (getcwd(curdir, MAXPATHLEN) == NULL) {
1473 (void)fprintf(stderr, "%s: getcwd: %s.\n",
1474 progname, strerror(errno));
1475 exit(2);
1476 }
1477
1478 MainParseArgs(argc, argv);
1479
1480 if (opts.enterFlag)
1481 printf("%s: Entering directory `%s'\n", progname, curdir);
1482
1483 if (stat(curdir, &sa) == -1) {
1484 (void)fprintf(stderr, "%s: %s: %s.\n",
1485 progname, curdir, strerror(errno));
1486 exit(2);
1487 }
1488
1489 #ifndef NO_PWD_OVERRIDE
1490 HandlePWD(&sa);
1491 #endif
1492 Global_Set(".CURDIR", curdir);
1493
1494 InitObjdir(machine, machine_arch);
1495
1496 Arch_Init();
1497 Suff_Init();
1498 Trace_Init(tracefile);
1499
1500 defaultNode = NULL;
1501 (void)time(&now);
1502
1503 Trace_Log(MAKESTART, NULL);
1504
1505 InitVarTargets();
1506
1507 InitDefSysIncPath(syspath);
1508 }
1509
1510 /*
1511 * Read the system makefile followed by either makefile, Makefile or the
1512 * files given by the -f option. Exit on parse errors.
1513 */
1514 static void
1515 main_ReadFiles(void)
1516 {
1517
1518 if (!opts.noBuiltins)
1519 ReadBuiltinRules();
1520
1521 if (!Lst_IsEmpty(&opts.makefiles))
1522 ReadAllMakefiles(&opts.makefiles);
1523 else
1524 ReadFirstDefaultMakefile();
1525 }
1526
1527 /* Compute the dependency graph. */
1528 static void
1529 main_PrepareMaking(void)
1530 {
1531 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1532 if (!opts.noBuiltins || opts.printVars == PVM_NONE) {
1533 (void)Var_Subst("${.MAKE.DEPENDFILE}",
1534 SCOPE_CMDLINE, VARE_WANTRES, &makeDependfile);
1535 if (makeDependfile[0] != '\0') {
1536 /* TODO: handle errors */
1537 doing_depend = true;
1538 (void)ReadMakefile(makeDependfile);
1539 doing_depend = false;
1540 }
1541 }
1542
1543 if (enterFlagObj)
1544 printf("%s: Entering directory `%s'\n", progname, objdir);
1545
1546 MakeMode();
1547
1548 {
1549 FStr makeflags = Var_Value(SCOPE_GLOBAL, MAKEFLAGS);
1550 Global_Append("MFLAGS", makeflags.str);
1551 FStr_Done(&makeflags);
1552 }
1553
1554 InitMaxJobs();
1555
1556 if (!opts.compatMake && !forceJobs)
1557 opts.compatMake = true;
1558
1559 if (!opts.compatMake)
1560 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1561 DEBUG5(JOB, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1562 jp_0, jp_1, opts.maxJobs, maxJobTokens, opts.compatMake ? 1 : 0);
1563
1564 if (opts.printVars == PVM_NONE)
1565 Main_ExportMAKEFLAGS(true); /* initial export */
1566
1567 InitVpath();
1568
1569 /*
1570 * Now that all search paths have been read for suffixes et al, it's
1571 * time to add the default search path to their lists...
1572 */
1573 Suff_ExtendPaths();
1574
1575 /*
1576 * Propagate attributes through :: dependency lists.
1577 */
1578 Targ_Propagate();
1579
1580 /* print the initial graph, if the user requested it */
1581 if (DEBUG(GRAPH1))
1582 Targ_PrintGraph(1);
1583 }
1584
1585 /*
1586 * Make the targets.
1587 * If the -v or -V options are given, print variables instead.
1588 * Return whether any of the targets is out-of-date.
1589 */
1590 static bool
1591 main_Run(void)
1592 {
1593 if (opts.printVars != PVM_NONE) {
1594 /* print the values of any variables requested by the user */
1595 doPrintVars();
1596 return false;
1597 } else {
1598 return runTargets();
1599 }
1600 }
1601
1602 /* Clean up after making the targets. */
1603 static void
1604 main_CleanUp(void)
1605 {
1606 #ifdef CLEANUP
1607 Lst_DoneCall(&opts.variables, free);
1608 Lst_Done(&opts.makefiles);
1609 Lst_DoneCall(&opts.create, free);
1610 #endif
1611
1612 if (DEBUG(GRAPH2))
1613 Targ_PrintGraph(2);
1614
1615 Trace_Log(MAKEEND, NULL);
1616
1617 if (enterFlagObj)
1618 printf("%s: Leaving directory `%s'\n", progname, objdir);
1619 if (opts.enterFlag)
1620 printf("%s: Leaving directory `%s'\n", progname, curdir);
1621
1622 #ifdef USE_META
1623 meta_finish();
1624 #endif
1625 Suff_End();
1626 Targ_End();
1627 Arch_End();
1628 Var_End();
1629 Parse_End();
1630 Dir_End();
1631 Job_End();
1632 Trace_End();
1633 Str_Intern_End();
1634 }
1635
1636 /* Determine the exit code. */
1637 static int
1638 main_Exit(bool outOfDate)
1639 {
1640 if (opts.strict && (main_errors > 0 || Parse_NumErrors() > 0))
1641 return 2; /* Not 1 so -q can distinguish error */
1642 return outOfDate ? 1 : 0;
1643 }
1644
1645 int
1646 main(int argc, char **argv)
1647 {
1648 bool outOfDate;
1649
1650 main_Init(argc, argv);
1651 main_ReadFiles();
1652 main_PrepareMaking();
1653 outOfDate = main_Run();
1654 main_CleanUp();
1655 return main_Exit(outOfDate);
1656 }
1657
1658 /*
1659 * Open and parse the given makefile, with all its side effects.
1660 * Return false if the file could not be opened.
1661 */
1662 static bool
1663 ReadMakefile(const char *fname)
1664 {
1665 int fd;
1666 char *name, *path = NULL;
1667
1668 if (strcmp(fname, "-") == 0) {
1669 Parse_File(NULL /*stdin*/, -1);
1670 Var_Set(SCOPE_INTERNAL, "MAKEFILE", "");
1671 } else {
1672 /* if we've chdir'd, rebuild the path name */
1673 if (strcmp(curdir, objdir) != 0 && *fname != '/') {
1674 path = str_concat3(curdir, "/", fname);
1675 fd = open(path, O_RDONLY);
1676 if (fd != -1) {
1677 fname = path;
1678 goto found;
1679 }
1680 free(path);
1681
1682 /* If curdir failed, try objdir (ala .depend) */
1683 path = str_concat3(objdir, "/", fname);
1684 fd = open(path, O_RDONLY);
1685 if (fd != -1) {
1686 fname = path;
1687 goto found;
1688 }
1689 } else {
1690 fd = open(fname, O_RDONLY);
1691 if (fd != -1)
1692 goto found;
1693 }
1694 /* look in -I and system include directories. */
1695 name = Dir_FindFile(fname, parseIncPath);
1696 if (name == NULL) {
1697 SearchPath *sysInc = Lst_IsEmpty(&sysIncPath->dirs)
1698 ? defSysIncPath : sysIncPath;
1699 name = Dir_FindFile(fname, sysInc);
1700 }
1701 if (name == NULL || (fd = open(name, O_RDONLY)) == -1) {
1702 free(name);
1703 free(path);
1704 return false;
1705 }
1706 fname = name;
1707 /*
1708 * set the MAKEFILE variable desired by System V fans -- the
1709 * placement of the setting here means it gets set to the last
1710 * makefile specified, as it is set by SysV make.
1711 */
1712 found:
1713 if (!doing_depend)
1714 Var_Set(SCOPE_INTERNAL, "MAKEFILE", fname);
1715 Parse_File(fname, fd);
1716 }
1717 free(path);
1718 return true;
1719 }
1720
1721 /*
1722 * Execute the command in cmd, and return its output (only stdout, not
1723 * stderr). In the output, replace newlines with spaces.
1724 *
1725 * Results:
1726 * The output of the command, can be empty.
1727 * *errfmt returns a format string describing the command failure,
1728 * if any, using a single %s conversion specification.
1729 * TODO: replace errfmt with an actual error message.
1730 */
1731 char *
1732 Cmd_Exec(const char *cmd, const char **errfmt)
1733 {
1734 const char *args[4]; /* Arguments for invoking the shell */
1735 int pipefds[2];
1736 int cpid; /* Child PID */
1737 int pid; /* PID from wait() */
1738 int status; /* command exit status */
1739 Buffer buf; /* buffer to store the result */
1740 ssize_t bytes_read;
1741 char *res; /* result */
1742 size_t res_len;
1743 char *cp;
1744 int savederr; /* saved errno */
1745
1746 *errfmt = NULL;
1747
1748 if (shellName == NULL)
1749 Shell_Init();
1750
1751 args[0] = shellName;
1752 args[1] = "-c";
1753 args[2] = cmd;
1754 args[3] = NULL;
1755
1756 if (pipe(pipefds) == -1) {
1757 *errfmt = "Couldn't create pipe for \"%s\"";
1758 goto bad;
1759 }
1760
1761 Var_ReexportVars();
1762
1763 switch (cpid = vfork()) {
1764 case 0:
1765 (void)close(pipefds[0]);
1766 (void)dup2(pipefds[1], 1);
1767 (void)close(pipefds[1]);
1768
1769 (void)execv(shellPath, UNCONST(args));
1770 _exit(1);
1771 /* NOTREACHED */
1772
1773 case -1:
1774 *errfmt = "Couldn't exec \"%s\"";
1775 goto bad;
1776
1777 default:
1778 (void)close(pipefds[1]); /* No need for the writing half */
1779
1780 savederr = 0;
1781 Buf_Init(&buf);
1782
1783 do {
1784 char result[BUFSIZ];
1785 bytes_read = read(pipefds[0], result, sizeof result);
1786 if (bytes_read > 0)
1787 Buf_AddBytes(&buf, result, (size_t)bytes_read);
1788 } while (bytes_read > 0 ||
1789 (bytes_read == -1 && errno == EINTR));
1790 if (bytes_read == -1)
1791 savederr = errno;
1792
1793 (void)close(pipefds[0]); /* Close the input side of the pipe. */
1794
1795 while ((pid = waitpid(cpid, &status, 0)) != cpid && pid >= 0)
1796 JobReapChild(pid, status, false);
1797
1798 res_len = buf.len;
1799 res = Buf_DoneData(&buf);
1800
1801 if (savederr != 0)
1802 *errfmt = "Couldn't read shell's output for \"%s\"";
1803
1804 if (WIFSIGNALED(status))
1805 *errfmt = "\"%s\" exited on a signal";
1806 else if (WEXITSTATUS(status) != 0)
1807 *errfmt = "\"%s\" returned non-zero status";
1808
1809 /* Convert newlines to spaces, strip the final newline. */
1810 if (res_len > 0 && res[res_len - 1] == '\n')
1811 res[res_len - 1] = '\0';
1812 for (cp = res; *cp != '\0'; cp++)
1813 if (*cp == '\n')
1814 *cp = ' ';
1815 break;
1816 }
1817 return res;
1818 bad:
1819 return bmake_strdup("");
1820 }
1821
1822 /*
1823 * Print a printf-style error message.
1824 *
1825 * In default mode, this error message has no consequences, for compatibility
1826 * reasons, in particular it does not affect the exit status. Only in lint
1827 * mode (-dL) it does.
1828 */
1829 void
1830 Error(const char *fmt, ...)
1831 {
1832 va_list ap;
1833 FILE *err_file;
1834
1835 err_file = opts.debug_file;
1836 if (err_file == stdout)
1837 err_file = stderr;
1838 (void)fflush(stdout);
1839 for (;;) {
1840 va_start(ap, fmt);
1841 fprintf(err_file, "%s: ", progname);
1842 (void)vfprintf(err_file, fmt, ap);
1843 va_end(ap);
1844 (void)fprintf(err_file, "\n");
1845 (void)fflush(err_file);
1846 if (err_file == stderr)
1847 break;
1848 err_file = stderr;
1849 }
1850 main_errors++;
1851 }
1852
1853 /*
1854 * Wait for any running jobs to finish, then produce an error message,
1855 * finally exit immediately.
1856 *
1857 * Exiting immediately differs from Parse_Error, which exits only after the
1858 * current top-level makefile has been parsed completely.
1859 */
1860 void
1861 Fatal(const char *fmt, ...)
1862 {
1863 va_list ap;
1864
1865 if (jobsRunning)
1866 Job_Wait();
1867
1868 (void)fflush(stdout);
1869 va_start(ap, fmt);
1870 (void)vfprintf(stderr, fmt, ap);
1871 va_end(ap);
1872 (void)fprintf(stderr, "\n");
1873 (void)fflush(stderr);
1874
1875 PrintOnError(NULL, NULL);
1876
1877 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1878 Targ_PrintGraph(2);
1879 Trace_Log(MAKEERROR, NULL);
1880 exit(2); /* Not 1 so -q can distinguish error */
1881 }
1882
1883 /*
1884 * Major exception once jobs are being created.
1885 * Kills all jobs, prints a message and exits.
1886 */
1887 void
1888 Punt(const char *fmt, ...)
1889 {
1890 va_list ap;
1891
1892 va_start(ap, fmt);
1893 (void)fflush(stdout);
1894 (void)fprintf(stderr, "%s: ", progname);
1895 (void)vfprintf(stderr, fmt, ap);
1896 va_end(ap);
1897 (void)fprintf(stderr, "\n");
1898 (void)fflush(stderr);
1899
1900 PrintOnError(NULL, NULL);
1901
1902 DieHorribly();
1903 }
1904
1905 /* Exit without giving a message. */
1906 void
1907 DieHorribly(void)
1908 {
1909 if (jobsRunning)
1910 Job_AbortAll();
1911 if (DEBUG(GRAPH2))
1912 Targ_PrintGraph(2);
1913 Trace_Log(MAKEERROR, NULL);
1914 exit(2); /* Not 1 so -q can distinguish error */
1915 }
1916
1917 /*
1918 * Called when aborting due to errors in child shell to signal abnormal exit.
1919 * The program exits.
1920 * Errors is the number of errors encountered in Make_Make.
1921 */
1922 void
1923 Finish(int errs)
1924 {
1925 if (shouldDieQuietly(NULL, -1))
1926 exit(2);
1927 Fatal("%d error%s", errs, errs == 1 ? "" : "s");
1928 }
1929
1930 bool
1931 unlink_file(const char *file)
1932 {
1933 struct stat st;
1934
1935 if (lstat(file, &st) == -1)
1936 return false;
1937
1938 if (S_ISDIR(st.st_mode)) {
1939 errno = EISDIR;
1940 return false;
1941 }
1942 return unlink(file) == 0;
1943 }
1944
1945 static void
1946 write_all(int fd, const void *data, size_t n)
1947 {
1948 const char *mem = data;
1949
1950 while (n > 0) {
1951 ssize_t written = write(fd, mem, n);
1952 if (written == -1 && errno == EAGAIN)
1953 continue;
1954 if (written == -1)
1955 break;
1956 mem += written;
1957 n -= (size_t)written;
1958 }
1959 }
1960
1961 /* Print why exec failed, avoiding stdio. */
1962 void MAKE_ATTR_DEAD
1963 execDie(const char *af, const char *av)
1964 {
1965 Buffer buf;
1966
1967 Buf_Init(&buf);
1968 Buf_AddStr(&buf, progname);
1969 Buf_AddStr(&buf, ": ");
1970 Buf_AddStr(&buf, af);
1971 Buf_AddStr(&buf, "(");
1972 Buf_AddStr(&buf, av);
1973 Buf_AddStr(&buf, ") failed (");
1974 Buf_AddStr(&buf, strerror(errno));
1975 Buf_AddStr(&buf, ")\n");
1976
1977 write_all(STDERR_FILENO, buf.data, buf.len);
1978
1979 Buf_Done(&buf);
1980 _exit(1);
1981 }
1982
1983 /* purge any relative paths */
1984 static void
1985 purge_relative_cached_realpaths(void)
1986 {
1987 HashEntry *he, *nhe;
1988 HashIter hi;
1989
1990 HashIter_Init(&hi, &cached_realpaths);
1991 he = HashIter_Next(&hi);
1992 while (he != NULL) {
1993 nhe = HashIter_Next(&hi);
1994 if (he->key[0] != '/') {
1995 DEBUG1(DIR, "cached_realpath: purging %s\n", he->key);
1996 HashTable_DeleteEntry(&cached_realpaths, he);
1997 /*
1998 * XXX: What about the allocated he->value? Either
1999 * free them or document why they cannot be freed.
2000 */
2001 }
2002 he = nhe;
2003 }
2004 }
2005
2006 char *
2007 cached_realpath(const char *pathname, char *resolved)
2008 {
2009 const char *rp;
2010
2011 if (pathname == NULL || pathname[0] == '\0')
2012 return NULL;
2013
2014 rp = HashTable_FindValue(&cached_realpaths, pathname);
2015 if (rp != NULL) {
2016 /* a hit */
2017 strncpy(resolved, rp, MAXPATHLEN);
2018 resolved[MAXPATHLEN - 1] = '\0';
2019 return resolved;
2020 }
2021
2022 rp = realpath(pathname, resolved);
2023 if (rp != NULL) {
2024 HashTable_Set(&cached_realpaths, pathname, bmake_strdup(rp));
2025 DEBUG2(DIR, "cached_realpath: %s -> %s\n", pathname, rp);
2026 return resolved;
2027 }
2028
2029 /* should we negative-cache? */
2030 return NULL;
2031 }
2032
2033 /*
2034 * Return true if we should die without noise.
2035 * For example our failing child was a sub-make or failure happened elsewhere.
2036 */
2037 bool
2038 shouldDieQuietly(GNode *gn, int bf)
2039 {
2040 static int quietly = -1;
2041
2042 if (quietly < 0) {
2043 if (DEBUG(JOB) ||
2044 !GetBooleanExpr("${.MAKE.DIE_QUIETLY}", true))
2045 quietly = 0;
2046 else if (bf >= 0)
2047 quietly = bf;
2048 else
2049 quietly = (gn != NULL && (gn->type & OP_MAKE)) ? 1 : 0;
2050 }
2051 return quietly != 0;
2052 }
2053
2054 static void
2055 SetErrorVars(GNode *gn)
2056 {
2057 StringListNode *ln;
2058
2059 /*
2060 * We can print this even if there is no .ERROR target.
2061 */
2062 Global_Set(".ERROR_TARGET", gn->name);
2063 Global_Delete(".ERROR_CMD");
2064
2065 for (ln = gn->commands.first; ln != NULL; ln = ln->next) {
2066 const char *cmd = ln->datum;
2067
2068 if (cmd == NULL)
2069 break;
2070 Global_Append(".ERROR_CMD", cmd);
2071 }
2072 }
2073
2074 /*
2075 * Print some helpful information in case of an error.
2076 * The caller should exit soon after calling this function.
2077 */
2078 void
2079 PrintOnError(GNode *gn, const char *msg)
2080 {
2081 static GNode *errorNode = NULL;
2082
2083 if (DEBUG(HASH)) {
2084 Targ_Stats();
2085 Var_Stats();
2086 }
2087
2088 if (errorNode != NULL)
2089 return; /* we've been here! */
2090
2091 if (msg != NULL)
2092 printf("%s", msg);
2093 printf("\n%s: stopped in %s\n", progname, curdir);
2094
2095 /* we generally want to keep quiet if a sub-make died */
2096 if (shouldDieQuietly(gn, -1))
2097 return;
2098
2099 if (gn != NULL)
2100 SetErrorVars(gn);
2101
2102 {
2103 char *errorVarsValues;
2104 (void)Var_Subst("${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
2105 SCOPE_GLOBAL, VARE_WANTRES, &errorVarsValues);
2106 /* TODO: handle errors */
2107 printf("%s", errorVarsValues);
2108 free(errorVarsValues);
2109 }
2110
2111 fflush(stdout);
2112
2113 /*
2114 * Finally, see if there is a .ERROR target, and run it if so.
2115 */
2116 errorNode = Targ_FindNode(".ERROR");
2117 if (errorNode != NULL) {
2118 errorNode->type |= OP_SPECIAL;
2119 Compat_Make(errorNode, errorNode);
2120 }
2121 }
2122
2123 void
2124 Main_ExportMAKEFLAGS(bool first)
2125 {
2126 static bool once = true;
2127 const char *expr;
2128 char *s;
2129
2130 if (once != first)
2131 return;
2132 once = false;
2133
2134 expr = "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}";
2135 (void)Var_Subst(expr, SCOPE_CMDLINE, VARE_WANTRES, &s);
2136 /* TODO: handle errors */
2137 if (s[0] != '\0') {
2138 #ifdef POSIX
2139 setenv("MAKEFLAGS", s, 1);
2140 #else
2141 setenv("MAKE", s, 1);
2142 #endif
2143 }
2144 }
2145
2146 char *
2147 getTmpdir(void)
2148 {
2149 static char *tmpdir = NULL;
2150 struct stat st;
2151
2152 if (tmpdir != NULL)
2153 return tmpdir;
2154
2155 /* Honor $TMPDIR but only if it is valid. Ensure it ends with '/'. */
2156 (void)Var_Subst("${TMPDIR:tA:U" _PATH_TMP ":S,/$,,W}/",
2157 SCOPE_GLOBAL, VARE_WANTRES, &tmpdir);
2158 /* TODO: handle errors */
2159
2160 if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
2161 free(tmpdir);
2162 tmpdir = bmake_strdup(_PATH_TMP);
2163 }
2164 return tmpdir;
2165 }
2166
2167 /*
2168 * Create and open a temp file using "pattern".
2169 * If out_fname is provided, set it to a copy of the filename created.
2170 * Otherwise unlink the file once open.
2171 */
2172 int
2173 mkTempFile(const char *pattern, char *tfile, size_t tfile_sz)
2174 {
2175 static char *tmpdir = NULL;
2176 char tbuf[MAXPATHLEN];
2177 int fd;
2178
2179 if (pattern == NULL)
2180 pattern = TMPPAT;
2181 if (tmpdir == NULL)
2182 tmpdir = getTmpdir();
2183 if (tfile == NULL) {
2184 tfile = tbuf;
2185 tfile_sz = sizeof tbuf;
2186 }
2187 if (pattern[0] == '/') {
2188 snprintf(tfile, tfile_sz, "%s", pattern);
2189 } else {
2190 snprintf(tfile, tfile_sz, "%s%s", tmpdir, pattern);
2191 }
2192 if ((fd = mkstemp(tfile)) < 0)
2193 Punt("Could not create temporary file %s: %s", tfile,
2194 strerror(errno));
2195 if (tfile == tbuf) {
2196 unlink(tfile); /* we just want the descriptor */
2197 }
2198 return fd;
2199 }
2200
2201 /*
2202 * Convert a string representation of a boolean into a boolean value.
2203 * Anything that looks like "No", "False", "Off", "0" etc. is false,
2204 * the empty string is the fallback, everything else is true.
2205 */
2206 bool
2207 ParseBoolean(const char *s, bool fallback)
2208 {
2209 char ch = ch_tolower(s[0]);
2210 if (ch == '\0')
2211 return fallback;
2212 if (ch == '0' || ch == 'f' || ch == 'n')
2213 return false;
2214 if (ch == 'o')
2215 return ch_tolower(s[1]) != 'f';
2216 return true;
2217 }
2218