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