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