main.c revision 1.602 1 /* $NetBSD: main.c,v 1.602 2023/11/02 05:40:49 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.602 2023/11/02 05:40:49 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 a 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 = end;
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 = end;
416 } else
417 d = 0.0;
418 if (d > 0.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: argument '%s' to option '-j' "
428 "must be a positive number\n",
429 progname, arg);
430 exit(2); /* Not 1 so -q can distinguish error */
431 }
432 snprintf(v, sizeof(v), "%d", opts.maxJobs);
433 Global_Append(MAKEFLAGS, "-j");
434 Global_Append(MAKEFLAGS, v);
435 Global_Set(".MAKE.JOBS", v);
436 maxJobTokens = opts.maxJobs;
437 }
438
439 static void
440 MainParseArgSysInc(const char *argvalue)
441 {
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 SearchPath_Add(parseIncPath, 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 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
1018 * since the value of curdir can vary depending on how we got
1019 * here. That is, sitting at a shell prompt (shell that provides $PWD)
1020 * or via subdir.mk, in which case it's likely a shell which does
1021 * not provide it.
1022 *
1023 * So, to stop it breaking this case only, we ignore PWD if
1024 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains an expression.
1025 */
1026 static void
1027 HandlePWD(const struct stat *curdir_st)
1028 {
1029 char *pwd;
1030 FStr makeobjdir;
1031 struct stat pwd_st;
1032
1033 if (ignorePWD || (pwd = getenv("PWD")) == NULL)
1034 return;
1035
1036 if (Var_Exists(SCOPE_CMDLINE, "MAKEOBJDIRPREFIX"))
1037 return;
1038
1039 makeobjdir = Var_Value(SCOPE_CMDLINE, "MAKEOBJDIR");
1040 if (makeobjdir.str != NULL && strchr(makeobjdir.str, '$') != NULL)
1041 goto ignore_pwd;
1042
1043 if (stat(pwd, &pwd_st) == 0 &&
1044 curdir_st->st_ino == pwd_st.st_ino &&
1045 curdir_st->st_dev == pwd_st.st_dev)
1046 (void)strncpy(curdir, pwd, MAXPATHLEN);
1047
1048 ignore_pwd:
1049 FStr_Done(&makeobjdir);
1050 }
1051 #endif
1052
1053 /*
1054 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that, MAKEOBJDIR is set
1055 * in the environment, try only that value and fall back to .CURDIR if it
1056 * does not exist.
1057 *
1058 * Otherwise, try _PATH_OBJDIR.MACHINE-MACHINE_ARCH, _PATH_OBJDIR.MACHINE,
1059 * and finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none of these
1060 * paths exist, just use .CURDIR.
1061 */
1062 static void
1063 InitObjdir(const char *machine, const char *machine_arch)
1064 {
1065 bool writable;
1066
1067 Dir_InitCur(curdir);
1068 writable = GetBooleanExpr("${MAKE_OBJDIR_CHECK_WRITABLE}", true);
1069 (void)Main_SetObjdir(false, "%s", curdir);
1070
1071 if (!SetVarObjdir(writable, "MAKEOBJDIRPREFIX", curdir) &&
1072 !SetVarObjdir(writable, "MAKEOBJDIR", "") &&
1073 !Main_SetObjdir(writable, "%s.%s-%s", _PATH_OBJDIR, machine, machine_arch) &&
1074 !Main_SetObjdir(writable, "%s.%s", _PATH_OBJDIR, machine) &&
1075 !Main_SetObjdir(writable, "%s", _PATH_OBJDIR))
1076 (void)Main_SetObjdir(writable, "%s%s", _PATH_OBJDIRPREFIX, curdir);
1077 }
1078
1079 /* get rid of resource limit on file descriptors */
1080 static void
1081 UnlimitFiles(void)
1082 {
1083 #if defined(MAKE_NATIVE) || (defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE))
1084 struct rlimit rl;
1085 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
1086 rl.rlim_cur != rl.rlim_max) {
1087 rl.rlim_cur = rl.rlim_max;
1088 (void)setrlimit(RLIMIT_NOFILE, &rl);
1089 }
1090 #endif
1091 }
1092
1093 static void
1094 CmdOpts_Init(void)
1095 {
1096 opts.compatMake = false;
1097 memset(&opts.debug, 0, sizeof(opts.debug));
1098 /* opts.debug_file has already been initialized earlier */
1099 opts.strict = false;
1100 opts.debugVflag = false;
1101 opts.checkEnvFirst = false;
1102 Lst_Init(&opts.makefiles);
1103 opts.ignoreErrors = false; /* Pay attention to non-zero returns */
1104 opts.maxJobs = 1;
1105 opts.keepgoing = false; /* Stop on error */
1106 opts.noRecursiveExecute = false; /* Execute all .MAKE targets */
1107 opts.noExecute = false; /* Execute all commands */
1108 opts.query = false;
1109 opts.noBuiltins = false; /* Read the built-in rules */
1110 opts.silent = false; /* Print commands as executed */
1111 opts.touch = false;
1112 opts.printVars = PVM_NONE;
1113 Lst_Init(&opts.variables);
1114 opts.parseWarnFatal = false;
1115 opts.enterFlag = false;
1116 opts.varNoExportEnv = false;
1117 Lst_Init(&opts.create);
1118 }
1119
1120 /*
1121 * Initialize MAKE and .MAKE to the path of the executable, so that it can be
1122 * found by execvp(3) and the shells, even after a chdir.
1123 *
1124 * If it's a relative path and contains a '/', resolve it to an absolute path.
1125 * Otherwise keep it as is, assuming it will be found in the PATH.
1126 */
1127 static void
1128 InitVarMake(const char *argv0)
1129 {
1130 const char *make = argv0;
1131
1132 if (argv0[0] != '/' && strchr(argv0, '/') != NULL) {
1133 char pathbuf[MAXPATHLEN];
1134 const char *abspath = cached_realpath(argv0, pathbuf);
1135 struct stat st;
1136 if (abspath != NULL && abspath[0] == '/' &&
1137 stat(make, &st) == 0)
1138 make = abspath;
1139 }
1140
1141 Global_Set("MAKE", make);
1142 Global_Set(".MAKE", make);
1143 }
1144
1145 /*
1146 * Add the directories from the colon-separated syspath to defSysIncPath.
1147 * After returning, the contents of syspath is unspecified.
1148 */
1149 static void
1150 InitDefSysIncPath(char *syspath)
1151 {
1152 static char defsyspath[] = _PATH_DEFSYSPATH;
1153 char *start, *cp;
1154
1155 /*
1156 * If no user-supplied system path was given (through the -m option)
1157 * add the directories from the DEFSYSPATH (more than one may be given
1158 * as dir1:...:dirn) to the system include path.
1159 */
1160 if (syspath == NULL || syspath[0] == '\0')
1161 syspath = defsyspath;
1162 else
1163 syspath = bmake_strdup(syspath);
1164
1165 for (start = syspath; *start != '\0'; start = cp) {
1166 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1167 continue;
1168 if (*cp == ':')
1169 *cp++ = '\0';
1170
1171 /* look for magic parent directory search string */
1172 if (strncmp(start, ".../", 4) == 0) {
1173 char *dir = Dir_FindHereOrAbove(curdir, start + 4);
1174 if (dir != NULL) {
1175 (void)SearchPath_Add(defSysIncPath, dir);
1176 free(dir);
1177 }
1178 } else {
1179 (void)SearchPath_Add(defSysIncPath, start);
1180 }
1181 }
1182
1183 if (syspath != defsyspath)
1184 free(syspath);
1185 }
1186
1187 static void
1188 ReadBuiltinRules(void)
1189 {
1190 StringListNode *ln;
1191 StringList sysMkFiles = LST_INIT;
1192
1193 SearchPath_Expand(
1194 Lst_IsEmpty(&sysIncPath->dirs) ? defSysIncPath : sysIncPath,
1195 _PATH_DEFSYSMK,
1196 &sysMkFiles);
1197 if (Lst_IsEmpty(&sysMkFiles))
1198 Fatal("%s: no system rules (%s).", progname, _PATH_DEFSYSMK);
1199
1200 for (ln = sysMkFiles.first; ln != NULL; ln = ln->next)
1201 if (ReadMakefile(ln->datum))
1202 break;
1203
1204 if (ln == NULL)
1205 Fatal("%s: cannot open %s.",
1206 progname, (const char *)sysMkFiles.first->datum);
1207
1208 Lst_DoneCall(&sysMkFiles, free);
1209 }
1210
1211 static void
1212 InitMaxJobs(void)
1213 {
1214 char *value;
1215 int n;
1216
1217 if (forceJobs || opts.compatMake ||
1218 !Var_Exists(SCOPE_GLOBAL, ".MAKE.JOBS"))
1219 return;
1220
1221 value = Var_Subst("${.MAKE.JOBS}", SCOPE_GLOBAL, VARE_WANTRES);
1222 /* TODO: handle errors */
1223 n = (int)strtol(value, NULL, 0);
1224 if (n < 1) {
1225 (void)fprintf(stderr,
1226 "%s: illegal value for .MAKE.JOBS "
1227 "-- must be positive integer!\n",
1228 progname);
1229 exit(2); /* Not 1 so -q can distinguish error */
1230 }
1231
1232 if (n != opts.maxJobs) {
1233 Global_Append(MAKEFLAGS, "-j");
1234 Global_Append(MAKEFLAGS, value);
1235 }
1236
1237 opts.maxJobs = n;
1238 maxJobTokens = opts.maxJobs;
1239 forceJobs = true;
1240 free(value);
1241 }
1242
1243 /*
1244 * For compatibility, look at the directories in the VPATH variable
1245 * and add them to the search path, if the variable is defined. The
1246 * variable's value is in the same format as the PATH environment
1247 * variable, i.e. <directory>:<directory>:<directory>...
1248 */
1249 static void
1250 InitVpath(void)
1251 {
1252 char *vpath, savec, *path;
1253 if (!Var_Exists(SCOPE_CMDLINE, "VPATH"))
1254 return;
1255
1256 vpath = Var_Subst("${VPATH}", SCOPE_CMDLINE, VARE_WANTRES);
1257 /* TODO: handle errors */
1258 path = vpath;
1259 do {
1260 char *cp;
1261 /* skip to end of directory */
1262 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1263 continue;
1264 /* Save terminator character so know when to stop */
1265 savec = *cp;
1266 *cp = '\0';
1267 /* Add directory to search path */
1268 (void)SearchPath_Add(&dirSearchPath, path);
1269 *cp = savec;
1270 path = cp + 1;
1271 } while (savec == ':');
1272 free(vpath);
1273 }
1274
1275 static void
1276 ReadAllMakefiles(const StringList *makefiles)
1277 {
1278 StringListNode *ln;
1279
1280 for (ln = makefiles->first; ln != NULL; ln = ln->next) {
1281 const char *fname = ln->datum;
1282 if (!ReadMakefile(fname))
1283 Fatal("%s: cannot open %s.", progname, fname);
1284 }
1285 }
1286
1287 static void
1288 ReadFirstDefaultMakefile(void)
1289 {
1290 StringList makefiles = LST_INIT;
1291 StringListNode *ln;
1292 char *prefs = Var_Subst("${.MAKE.MAKEFILE_PREFERENCE}",
1293 SCOPE_CMDLINE, VARE_WANTRES);
1294 /* TODO: handle errors */
1295
1296 (void)str2Lst_Append(&makefiles, prefs);
1297
1298 for (ln = makefiles.first; ln != NULL; ln = ln->next)
1299 if (ReadMakefile(ln->datum))
1300 break;
1301
1302 Lst_Done(&makefiles);
1303 free(prefs);
1304 }
1305
1306 /*
1307 * Initialize variables such as MAKE, MACHINE, .MAKEFLAGS.
1308 * Initialize a few modules.
1309 * Parse the arguments from MAKEFLAGS and the command line.
1310 */
1311 static void
1312 main_Init(int argc, char **argv)
1313 {
1314 struct stat sa;
1315 const char *machine;
1316 const char *machine_arch;
1317 char *syspath = getenv("MAKESYSPATH");
1318 struct utsname utsname;
1319
1320 /* default to writing debug to stderr */
1321 opts.debug_file = stderr;
1322
1323 Str_Intern_Init();
1324 HashTable_Init(&cached_realpaths);
1325
1326 #ifdef SIGINFO
1327 (void)bmake_signal(SIGINFO, siginfo);
1328 #endif
1329
1330 InitRandom();
1331
1332 progname = str_basename(argv[0]);
1333
1334 UnlimitFiles();
1335
1336 if (uname(&utsname) == -1) {
1337 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
1338 strerror(errno));
1339 exit(2);
1340 }
1341
1342 machine = InitVarMachine(&utsname);
1343 machine_arch = InitVarMachineArch();
1344
1345 myPid = getpid(); /* remember this for vFork() */
1346
1347 /* Just in case MAKEOBJDIR wants us to do something tricky. */
1348 Targ_Init();
1349 Var_Init();
1350 Global_Set_ReadOnly(".MAKE.OS", utsname.sysname);
1351 Global_Set("MACHINE", machine);
1352 Global_Set("MACHINE_ARCH", machine_arch);
1353 #ifdef MAKE_VERSION
1354 Global_Set("MAKE_VERSION", MAKE_VERSION);
1355 #endif
1356 Global_Set_ReadOnly(".newline", "\n");
1357 #ifndef MAKEFILE_PREFERENCE_LIST
1358 /* This is the traditional preference for makefiles. */
1359 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
1360 #endif
1361 Global_Set(".MAKE.MAKEFILE_PREFERENCE", MAKEFILE_PREFERENCE_LIST);
1362 Global_Set(".MAKE.DEPENDFILE", ".depend");
1363 /* Tell makefiles like jobs.mk whether we support -jC */
1364 #ifdef _SC_NPROCESSORS_ONLN
1365 Global_Set_ReadOnly(".MAKE.JOBS.C", "yes");
1366 #else
1367 Global_Set_ReadOnly(".MAKE.JOBS.C", "no");
1368 #endif
1369
1370 CmdOpts_Init();
1371 allPrecious = false; /* Remove targets when interrupted */
1372 deleteOnError = false; /* Historical default behavior */
1373 jobsRunning = false;
1374
1375 maxJobTokens = opts.maxJobs;
1376 ignorePWD = false;
1377
1378 /*
1379 * Initialize the parsing, directory and variable modules to prepare
1380 * for the reading of inclusion paths and variable settings on the
1381 * command line
1382 */
1383
1384 /*
1385 * Initialize various variables.
1386 * MAKE also gets this name, for compatibility
1387 * .MAKEFLAGS gets set to the empty string just in case.
1388 * MFLAGS also gets initialized empty, for compatibility.
1389 */
1390 Parse_Init();
1391 InitVarMake(argv[0]);
1392 Global_Set(MAKEFLAGS, "");
1393 Global_Set(".MAKEOVERRIDES", "");
1394 Global_Set("MFLAGS", "");
1395 Global_Set(".ALLTARGETS", "");
1396 Var_Set(SCOPE_CMDLINE, ".MAKE.LEVEL.ENV", MAKE_LEVEL_ENV);
1397
1398 /* Set some other useful variables. */
1399 {
1400 char buf[64], *ep = getenv(MAKE_LEVEL_ENV);
1401
1402 makelevel = ep != NULL && ep[0] != '\0' ? atoi(ep) : 0;
1403 if (makelevel < 0)
1404 makelevel = 0;
1405 snprintf(buf, sizeof buf, "%d", makelevel);
1406 Global_Set(".MAKE.LEVEL", buf);
1407 snprintf(buf, sizeof buf, "%u", myPid);
1408 Global_Set_ReadOnly(".MAKE.PID", buf);
1409 snprintf(buf, sizeof buf, "%u", getppid());
1410 Global_Set_ReadOnly(".MAKE.PPID", buf);
1411 snprintf(buf, sizeof buf, "%u", getuid());
1412 Global_Set_ReadOnly(".MAKE.UID", buf);
1413 snprintf(buf, sizeof buf, "%u", getgid());
1414 Global_Set_ReadOnly(".MAKE.GID", buf);
1415 }
1416 if (makelevel > 0) {
1417 char pn[1024];
1418 snprintf(pn, sizeof pn, "%s[%d]", progname, makelevel);
1419 progname = bmake_strdup(pn);
1420 }
1421
1422 #ifdef USE_META
1423 meta_init();
1424 #endif
1425 Dir_Init();
1426
1427 #ifdef POSIX
1428 {
1429 char *makeflags = explode(getenv("MAKEFLAGS"));
1430 Main_ParseArgLine(makeflags);
1431 free(makeflags);
1432 }
1433 #else
1434 /*
1435 * First snag any flags out of the MAKE environment variable.
1436 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
1437 * in a different format).
1438 */
1439 Main_ParseArgLine(getenv("MAKE"));
1440 #endif
1441
1442 if (getcwd(curdir, MAXPATHLEN) == NULL) {
1443 (void)fprintf(stderr, "%s: getcwd: %s.\n",
1444 progname, strerror(errno));
1445 exit(2);
1446 }
1447
1448 MainParseArgs(argc, argv);
1449
1450 if (opts.enterFlag)
1451 printf("%s: Entering directory `%s'\n", progname, curdir);
1452
1453 if (stat(curdir, &sa) == -1) {
1454 (void)fprintf(stderr, "%s: %s: %s.\n",
1455 progname, curdir, strerror(errno));
1456 exit(2);
1457 }
1458
1459 #ifndef NO_PWD_OVERRIDE
1460 HandlePWD(&sa);
1461 #endif
1462 Global_Set(".CURDIR", curdir);
1463
1464 InitObjdir(machine, machine_arch);
1465
1466 Arch_Init();
1467 Suff_Init();
1468 Trace_Init(tracefile);
1469
1470 defaultNode = NULL;
1471 (void)time(&now);
1472
1473 Trace_Log(MAKESTART, NULL);
1474
1475 InitVarTargets();
1476
1477 InitDefSysIncPath(syspath);
1478 }
1479
1480 /*
1481 * Read the system makefile followed by either makefile, Makefile or the
1482 * files given by the -f option. Exit on parse errors.
1483 */
1484 static void
1485 main_ReadFiles(void)
1486 {
1487
1488 if (Lst_IsEmpty(&sysIncPath->dirs))
1489 SearchPath_AddAll(sysIncPath, defSysIncPath);
1490
1491 Dir_SetSYSPATH();
1492 if (!opts.noBuiltins)
1493 ReadBuiltinRules();
1494
1495 posix_state = PS_MAYBE_NEXT_LINE;
1496 if (!Lst_IsEmpty(&opts.makefiles))
1497 ReadAllMakefiles(&opts.makefiles);
1498 else
1499 ReadFirstDefaultMakefile();
1500 }
1501
1502 /* Compute the dependency graph. */
1503 static void
1504 main_PrepareMaking(void)
1505 {
1506 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1507 if (!opts.noBuiltins || opts.printVars == PVM_NONE) {
1508 makeDependfile = Var_Subst("${.MAKE.DEPENDFILE}",
1509 SCOPE_CMDLINE, VARE_WANTRES);
1510 if (makeDependfile[0] != '\0') {
1511 /* TODO: handle errors */
1512 doing_depend = true;
1513 (void)ReadMakefile(makeDependfile);
1514 doing_depend = false;
1515 }
1516 }
1517
1518 if (enterFlagObj)
1519 printf("%s: Entering directory `%s'\n", progname, objdir);
1520
1521 MakeMode();
1522
1523 {
1524 FStr makeflags = Var_Value(SCOPE_GLOBAL, MAKEFLAGS);
1525 Global_Append("MFLAGS", makeflags.str);
1526 FStr_Done(&makeflags);
1527 }
1528
1529 InitMaxJobs();
1530
1531 if (!opts.compatMake && !forceJobs)
1532 opts.compatMake = true;
1533
1534 if (!opts.compatMake)
1535 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1536 DEBUG5(JOB, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1537 jp_0, jp_1, opts.maxJobs, maxJobTokens, opts.compatMake ? 1 : 0);
1538
1539 if (opts.printVars == PVM_NONE)
1540 Main_ExportMAKEFLAGS(true); /* initial export */
1541
1542 InitVpath();
1543
1544 /*
1545 * Now that all search paths have been read for suffixes et al, it's
1546 * time to add the default search path to their lists...
1547 */
1548 Suff_ExtendPaths();
1549
1550 /*
1551 * Propagate attributes through :: dependency lists.
1552 */
1553 Targ_Propagate();
1554
1555 /* print the initial graph, if the user requested it */
1556 if (DEBUG(GRAPH1))
1557 Targ_PrintGraph(1);
1558 }
1559
1560 /*
1561 * Make the targets.
1562 * If the -v or -V options are given, print variables instead.
1563 * Return whether any of the targets is out-of-date.
1564 */
1565 static bool
1566 main_Run(void)
1567 {
1568 if (opts.printVars != PVM_NONE) {
1569 /* print the values of any variables requested by the user */
1570 doPrintVars();
1571 return false;
1572 } else {
1573 return runTargets();
1574 }
1575 }
1576
1577 /* Clean up after making the targets. */
1578 static void
1579 main_CleanUp(void)
1580 {
1581 #ifdef CLEANUP
1582 Lst_DoneCall(&opts.variables, free);
1583 Lst_DoneCall(&opts.makefiles, free);
1584 Lst_DoneCall(&opts.create, free);
1585 #endif
1586
1587 if (DEBUG(GRAPH2))
1588 Targ_PrintGraph(2);
1589
1590 Trace_Log(MAKEEND, NULL);
1591
1592 if (enterFlagObj)
1593 printf("%s: Leaving directory `%s'\n", progname, objdir);
1594 if (opts.enterFlag)
1595 printf("%s: Leaving directory `%s'\n", progname, curdir);
1596
1597 #ifdef USE_META
1598 meta_finish();
1599 #endif
1600 Suff_End();
1601 Targ_End();
1602 Arch_End();
1603 Var_End();
1604 Parse_End();
1605 Dir_End();
1606 Job_End();
1607 Trace_End();
1608 Str_Intern_End();
1609 }
1610
1611 /* Determine the exit code. */
1612 static int
1613 main_Exit(bool outOfDate)
1614 {
1615 if (opts.strict && (main_errors > 0 || Parse_NumErrors() > 0))
1616 return 2; /* Not 1 so -q can distinguish error */
1617 return outOfDate ? 1 : 0;
1618 }
1619
1620 int
1621 main(int argc, char **argv)
1622 {
1623 bool outOfDate;
1624
1625 main_Init(argc, argv);
1626 main_ReadFiles();
1627 main_PrepareMaking();
1628 outOfDate = main_Run();
1629 main_CleanUp();
1630 return main_Exit(outOfDate);
1631 }
1632
1633 /*
1634 * Open and parse the given makefile, with all its side effects.
1635 * Return false if the file could not be opened.
1636 */
1637 static bool
1638 ReadMakefile(const char *fname)
1639 {
1640 int fd;
1641 char *name, *path = NULL;
1642
1643 if (strcmp(fname, "-") == 0) {
1644 Parse_File("(stdin)", -1);
1645 Var_Set(SCOPE_INTERNAL, "MAKEFILE", "");
1646 } else {
1647 /* if we've chdir'd, rebuild the path name */
1648 if (strcmp(curdir, objdir) != 0 && *fname != '/') {
1649 path = str_concat3(curdir, "/", fname);
1650 fd = open(path, O_RDONLY);
1651 if (fd != -1) {
1652 fname = path;
1653 goto found;
1654 }
1655 free(path);
1656
1657 /* If curdir failed, try objdir (ala .depend) */
1658 path = str_concat3(objdir, "/", fname);
1659 fd = open(path, O_RDONLY);
1660 if (fd != -1) {
1661 fname = path;
1662 goto found;
1663 }
1664 } else {
1665 fd = open(fname, O_RDONLY);
1666 if (fd != -1)
1667 goto found;
1668 }
1669 /* look in -I and system include directories. */
1670 name = Dir_FindFile(fname, parseIncPath);
1671 if (name == NULL) {
1672 SearchPath *sysInc = Lst_IsEmpty(&sysIncPath->dirs)
1673 ? defSysIncPath : sysIncPath;
1674 name = Dir_FindFile(fname, sysInc);
1675 }
1676 if (name == NULL || (fd = open(name, O_RDONLY)) == -1) {
1677 free(name);
1678 free(path);
1679 return false;
1680 }
1681 fname = name;
1682 /*
1683 * set the MAKEFILE variable desired by System V fans -- the
1684 * placement of the setting here means it gets set to the last
1685 * makefile specified, as it is set by SysV make.
1686 */
1687 found:
1688 if (!doing_depend)
1689 Var_Set(SCOPE_INTERNAL, "MAKEFILE", fname);
1690 Parse_File(fname, fd);
1691 }
1692 free(path);
1693 return true;
1694 }
1695
1696 /*
1697 * Execute the command in cmd, and return its output (only stdout, not
1698 * stderr, possibly empty). In the output, replace newlines with spaces.
1699 */
1700 char *
1701 Cmd_Exec(const char *cmd, char **error)
1702 {
1703 const char *args[4]; /* Arguments for invoking the shell */
1704 int pipefds[2];
1705 int cpid; /* Child PID */
1706 int pid; /* PID from wait() */
1707 int status; /* command exit status */
1708 Buffer buf; /* buffer to store the result */
1709 ssize_t bytes_read;
1710 char *output;
1711 char *cp;
1712 int saved_errno;
1713
1714 if (shellName == NULL)
1715 Shell_Init();
1716
1717 args[0] = shellName;
1718 args[1] = "-c";
1719 args[2] = cmd;
1720 args[3] = NULL;
1721 DEBUG1(VAR, "Capturing the output of command \"%s\"\n", cmd);
1722
1723 if (pipe(pipefds) == -1) {
1724 *error = str_concat3(
1725 "Couldn't create pipe for \"", cmd, "\"");
1726 return bmake_strdup("");
1727 }
1728
1729 Var_ReexportVars();
1730
1731 switch (cpid = vfork()) {
1732 case 0:
1733 (void)close(pipefds[0]);
1734 (void)dup2(pipefds[1], STDOUT_FILENO);
1735 (void)close(pipefds[1]);
1736
1737 (void)execv(shellPath, UNCONST(args));
1738 _exit(1);
1739 /* NOTREACHED */
1740
1741 case -1:
1742 *error = str_concat3("Couldn't exec \"", cmd, "\"");
1743 return bmake_strdup("");
1744 }
1745
1746 (void)close(pipefds[1]); /* No need for the writing half */
1747
1748 saved_errno = 0;
1749 Buf_Init(&buf);
1750
1751 do {
1752 char result[BUFSIZ];
1753 bytes_read = read(pipefds[0], result, sizeof result);
1754 if (bytes_read > 0)
1755 Buf_AddBytes(&buf, result, (size_t)bytes_read);
1756 } while (bytes_read > 0 || (bytes_read == -1 && errno == EINTR));
1757 if (bytes_read == -1)
1758 saved_errno = errno;
1759
1760 (void)close(pipefds[0]); /* Close the input side of the pipe. */
1761
1762 while ((pid = waitpid(cpid, &status, 0)) != cpid && pid >= 0)
1763 JobReapChild(pid, status, false);
1764
1765 if (Buf_EndsWith(&buf, '\n'))
1766 buf.data[buf.len - 1] = '\0';
1767
1768 output = Buf_DoneData(&buf);
1769 for (cp = output; *cp != '\0'; cp++)
1770 if (*cp == '\n')
1771 *cp = ' ';
1772
1773 if (WIFSIGNALED(status))
1774 *error = str_concat3("\"", cmd, "\" exited on a signal");
1775 else if (WEXITSTATUS(status) != 0)
1776 *error = str_concat3(
1777 "\"", cmd, "\" returned non-zero status");
1778 else if (saved_errno != 0)
1779 *error = str_concat3(
1780 "Couldn't read shell's output for \"", cmd, "\"");
1781 else
1782 *error = NULL;
1783 return output;
1784 }
1785
1786 /*
1787 * Print a printf-style error message.
1788 *
1789 * In default mode, this error message has no consequences, for compatibility
1790 * reasons, in particular it does not affect the exit status. Only in lint
1791 * mode (-dL) it does.
1792 */
1793 void
1794 Error(const char *fmt, ...)
1795 {
1796 va_list ap;
1797 FILE *f;
1798
1799 f = opts.debug_file;
1800 if (f == stdout)
1801 f = stderr;
1802 (void)fflush(stdout);
1803
1804 for (;;) {
1805 fprintf(f, "%s: ", progname);
1806 va_start(ap, fmt);
1807 (void)vfprintf(f, fmt, ap);
1808 va_end(ap);
1809 (void)fprintf(f, "\n");
1810 (void)fflush(f);
1811 if (f == stderr)
1812 break;
1813 f = stderr;
1814 }
1815 main_errors++;
1816 }
1817
1818 /*
1819 * Wait for any running jobs to finish, then produce an error message,
1820 * finally exit immediately.
1821 *
1822 * Exiting immediately differs from Parse_Error, which exits only after the
1823 * current top-level makefile has been parsed completely.
1824 */
1825 void
1826 Fatal(const char *fmt, ...)
1827 {
1828 va_list ap;
1829
1830 if (jobsRunning)
1831 Job_Wait();
1832
1833 (void)fflush(stdout);
1834 va_start(ap, fmt);
1835 (void)vfprintf(stderr, fmt, ap);
1836 va_end(ap);
1837 (void)fprintf(stderr, "\n");
1838 (void)fflush(stderr);
1839 PrintStackTrace(true);
1840
1841 PrintOnError(NULL, "\n");
1842
1843 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1844 Targ_PrintGraph(2);
1845 Trace_Log(MAKEERROR, NULL);
1846 exit(2); /* Not 1 so -q can distinguish error */
1847 }
1848
1849 /*
1850 * Major exception once jobs are being created.
1851 * Kills all jobs, prints a message and exits.
1852 */
1853 void
1854 Punt(const char *fmt, ...)
1855 {
1856 va_list ap;
1857
1858 (void)fflush(stdout);
1859 (void)fprintf(stderr, "%s: ", progname);
1860 va_start(ap, fmt);
1861 (void)vfprintf(stderr, fmt, ap);
1862 va_end(ap);
1863 (void)fprintf(stderr, "\n");
1864 (void)fflush(stderr);
1865
1866 PrintOnError(NULL, "\n");
1867
1868 DieHorribly();
1869 }
1870
1871 /* Exit without giving a message. */
1872 void
1873 DieHorribly(void)
1874 {
1875 if (jobsRunning)
1876 Job_AbortAll();
1877 if (DEBUG(GRAPH2))
1878 Targ_PrintGraph(2);
1879 Trace_Log(MAKEERROR, NULL);
1880 exit(2); /* Not 1 so -q can distinguish error */
1881 }
1882
1883 /*
1884 * Called when aborting due to errors in child shell to signal abnormal exit.
1885 * The program exits.
1886 * Errors is the number of errors encountered in Make_Make.
1887 */
1888 void
1889 Finish(int errs)
1890 {
1891 if (shouldDieQuietly(NULL, -1))
1892 exit(2);
1893 Fatal("%d error%s", errs, errs == 1 ? "" : "s");
1894 }
1895
1896 int
1897 unlink_file(const char *file)
1898 {
1899 struct stat st;
1900
1901 if (lstat(file, &st) == -1)
1902 return -1;
1903
1904 if (S_ISDIR(st.st_mode)) {
1905 /*
1906 * POSIX says for unlink: "The path argument shall not name
1907 * a directory unless [...]".
1908 */
1909 errno = EISDIR;
1910 return -1;
1911 }
1912 return unlink(file);
1913 }
1914
1915 static void
1916 write_all(int fd, const void *data, size_t n)
1917 {
1918 const char *mem = data;
1919
1920 while (n > 0) {
1921 ssize_t written = write(fd, mem, n);
1922 /* XXX: Should this EAGAIN be EINTR? */
1923 if (written == -1 && errno == EAGAIN)
1924 continue;
1925 if (written == -1)
1926 break;
1927 mem += written;
1928 n -= (size_t)written;
1929 }
1930 }
1931
1932 /* Print why exec failed, avoiding stdio. */
1933 void MAKE_ATTR_DEAD
1934 execDie(const char *af, const char *av)
1935 {
1936 Buffer buf;
1937
1938 Buf_Init(&buf);
1939 Buf_AddStr(&buf, progname);
1940 Buf_AddStr(&buf, ": ");
1941 Buf_AddStr(&buf, af);
1942 Buf_AddStr(&buf, "(");
1943 Buf_AddStr(&buf, av);
1944 Buf_AddStr(&buf, ") failed (");
1945 Buf_AddStr(&buf, strerror(errno));
1946 Buf_AddStr(&buf, ")\n");
1947
1948 write_all(STDERR_FILENO, buf.data, buf.len);
1949
1950 Buf_Done(&buf);
1951 _exit(1);
1952 }
1953
1954 static void
1955 purge_relative_cached_realpaths(void)
1956 {
1957 HashEntry *he, *nhe;
1958 HashIter hi;
1959
1960 HashIter_Init(&hi, &cached_realpaths);
1961 he = HashIter_Next(&hi);
1962 while (he != NULL) {
1963 nhe = HashIter_Next(&hi);
1964 if (he->key[0] != '/') {
1965 DEBUG1(DIR, "cached_realpath: purging %s\n", he->key);
1966 HashTable_DeleteEntry(&cached_realpaths, he);
1967 /*
1968 * XXX: What about the allocated he->value? Either
1969 * free them or document why they cannot be freed.
1970 */
1971 }
1972 he = nhe;
1973 }
1974 }
1975
1976 const char *
1977 cached_realpath(const char *pathname, char *resolved)
1978 {
1979 const char *rp;
1980
1981 if (pathname == NULL || pathname[0] == '\0')
1982 return NULL;
1983
1984 rp = HashTable_FindValue(&cached_realpaths, pathname);
1985 if (rp != NULL) {
1986 /* a hit */
1987 strncpy(resolved, rp, MAXPATHLEN);
1988 resolved[MAXPATHLEN - 1] = '\0';
1989 return resolved;
1990 }
1991
1992 rp = realpath(pathname, resolved);
1993 if (rp != NULL) {
1994 HashTable_Set(&cached_realpaths, pathname, bmake_strdup(rp));
1995 DEBUG2(DIR, "cached_realpath: %s -> %s\n", pathname, rp);
1996 return resolved;
1997 }
1998
1999 /* should we negative-cache? */
2000 return NULL;
2001 }
2002
2003 /*
2004 * Return true if we should die without noise.
2005 * For example our failing child was a sub-make or failure happened elsewhere.
2006 */
2007 bool
2008 shouldDieQuietly(GNode *gn, int bf)
2009 {
2010 static int quietly = -1;
2011
2012 if (quietly < 0) {
2013 if (DEBUG(JOB) ||
2014 !GetBooleanExpr("${.MAKE.DIE_QUIETLY}", true))
2015 quietly = 0;
2016 else if (bf >= 0)
2017 quietly = bf;
2018 else
2019 quietly = (gn != NULL && (gn->type & OP_MAKE)) ? 1 : 0;
2020 }
2021 return quietly != 0;
2022 }
2023
2024 static void
2025 SetErrorVars(GNode *gn)
2026 {
2027 StringListNode *ln;
2028
2029 /*
2030 * We can print this even if there is no .ERROR target.
2031 */
2032 Global_Set(".ERROR_TARGET", gn->name);
2033 Global_Delete(".ERROR_CMD");
2034
2035 for (ln = gn->commands.first; ln != NULL; ln = ln->next) {
2036 const char *cmd = ln->datum;
2037
2038 if (cmd == NULL)
2039 break;
2040 Global_Append(".ERROR_CMD", cmd);
2041 }
2042 }
2043
2044 /*
2045 * Print some helpful information in case of an error.
2046 * The caller should exit soon after calling this function.
2047 */
2048 void
2049 PrintOnError(GNode *gn, const char *msg)
2050 {
2051 static GNode *errorNode = NULL;
2052
2053 if (DEBUG(HASH)) {
2054 Targ_Stats();
2055 Var_Stats();
2056 }
2057
2058 if (errorNode != NULL)
2059 return; /* we've been here! */
2060
2061 printf("%s%s: stopped in %s\n", msg, progname, curdir);
2062
2063 /* we generally want to keep quiet if a sub-make died */
2064 if (shouldDieQuietly(gn, -1))
2065 return;
2066
2067 if (gn != NULL)
2068 SetErrorVars(gn);
2069
2070 {
2071 char *errorVarsValues = Var_Subst(
2072 "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
2073 SCOPE_GLOBAL, VARE_WANTRES);
2074 /* TODO: handle errors */
2075 printf("%s", errorVarsValues);
2076 free(errorVarsValues);
2077 }
2078
2079 fflush(stdout);
2080
2081 /*
2082 * Finally, see if there is a .ERROR target, and run it if so.
2083 */
2084 errorNode = Targ_FindNode(".ERROR");
2085 if (errorNode != NULL) {
2086 errorNode->type |= OP_SPECIAL;
2087 Compat_Make(errorNode, errorNode);
2088 }
2089 }
2090
2091 void
2092 Main_ExportMAKEFLAGS(bool first)
2093 {
2094 static bool once = true;
2095 char *flags;
2096
2097 if (once != first)
2098 return;
2099 once = false;
2100
2101 flags = Var_Subst(
2102 "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
2103 SCOPE_CMDLINE, VARE_WANTRES);
2104 /* TODO: handle errors */
2105 if (flags[0] != '\0') {
2106 #ifdef POSIX
2107 setenv("MAKEFLAGS", flags, 1);
2108 #else
2109 setenv("MAKE", flags, 1);
2110 #endif
2111 }
2112 }
2113
2114 char *
2115 getTmpdir(void)
2116 {
2117 static char *tmpdir = NULL;
2118 struct stat st;
2119
2120 if (tmpdir != NULL)
2121 return tmpdir;
2122
2123 /* Honor $TMPDIR if it is valid, strip a trailing '/'. */
2124 tmpdir = Var_Subst("${TMPDIR:tA:U" _PATH_TMP ":S,/$,,W}/",
2125 SCOPE_GLOBAL, VARE_WANTRES);
2126 /* TODO: handle errors */
2127
2128 if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
2129 free(tmpdir);
2130 tmpdir = bmake_strdup(_PATH_TMP);
2131 }
2132 return tmpdir;
2133 }
2134
2135 /*
2136 * Create and open a temp file using "pattern".
2137 * If out_fname is provided, set it to a copy of the filename created.
2138 * Otherwise unlink the file once open.
2139 */
2140 int
2141 mkTempFile(const char *pattern, char *tfile, size_t tfile_sz)
2142 {
2143 static char *tmpdir = NULL;
2144 char tbuf[MAXPATHLEN];
2145 int fd;
2146
2147 if (pattern == NULL)
2148 pattern = TMPPAT;
2149 if (tmpdir == NULL)
2150 tmpdir = getTmpdir();
2151 if (tfile == NULL) {
2152 tfile = tbuf;
2153 tfile_sz = sizeof tbuf;
2154 }
2155
2156 if (pattern[0] == '/')
2157 snprintf(tfile, tfile_sz, "%s", pattern);
2158 else
2159 snprintf(tfile, tfile_sz, "%s%s", tmpdir, pattern);
2160
2161 if ((fd = mkstemp(tfile)) < 0)
2162 Punt("Could not create temporary file %s: %s", tfile,
2163 strerror(errno));
2164 if (tfile == tbuf)
2165 unlink(tfile); /* we just want the descriptor */
2166
2167 return fd;
2168 }
2169
2170 /*
2171 * Convert a string representation of a boolean into a boolean value.
2172 * Anything that looks like "No", "False", "Off", "0" etc. is false,
2173 * the empty string is the fallback, everything else is true.
2174 */
2175 bool
2176 ParseBoolean(const char *s, bool fallback)
2177 {
2178 char ch = ch_tolower(s[0]);
2179 if (ch == '\0')
2180 return fallback;
2181 if (ch == '0' || ch == 'f' || ch == 'n')
2182 return false;
2183 if (ch == 'o')
2184 return ch_tolower(s[1]) != 'f';
2185 return true;
2186 }
2187