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