main.c revision 1.565 1 /* $NetBSD: main.c,v 1.565 2022/01/01 21:41:50 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.565 2022/01/01 21:41:50 rillig Exp $");
115 #if defined(MAKE_NATIVE) && !defined(lint)
116 __COPYRIGHT("@(#) Copyright (c) 1988, 1989, 1990, 1993 "
117 "The Regents of the University of California. "
118 "All rights reserved.");
119 #endif
120
121 CmdOpts opts;
122 time_t now; /* Time at start of make */
123 GNode *defaultNode; /* .DEFAULT node */
124 bool allPrecious; /* .PRECIOUS given on line by itself */
125 bool deleteOnError; /* .DELETE_ON_ERROR: set */
126
127 static int maxJobTokens; /* -j argument */
128 bool enterFlagObj; /* -w and objdir != srcdir */
129
130 static int jp_0 = -1, jp_1 = -1; /* ends of parent job pipe */
131 bool doing_depend; /* Set while reading .depend */
132 static bool jobsRunning; /* true if the jobs might be running */
133 static const char *tracefile;
134 static bool ReadMakefile(const char *);
135 static void purge_relative_cached_realpaths(void);
136
137 static bool ignorePWD; /* if we use -C, PWD is meaningless */
138 static char objdir[MAXPATHLEN + 1]; /* where we chdir'ed to */
139 char curdir[MAXPATHLEN + 1]; /* Startup directory */
140 const char *progname;
141 char *makeDependfile;
142 pid_t myPid;
143 int makelevel;
144
145 bool forceJobs = false;
146 static int main_errors = 0;
147 static HashTable cached_realpaths;
148
149 /*
150 * For compatibility with the POSIX version of MAKEFLAGS that includes
151 * all the options without '-', convert 'flags' to '-f -l -a -g -s'.
152 */
153 static char *
154 explode(const char *flags)
155 {
156 char *exploded, *ep;
157 const char *p;
158
159 if (flags == NULL)
160 return NULL;
161
162 for (p = flags; *p != '\0'; p++)
163 if (!ch_isalpha(*p))
164 return bmake_strdup(flags);
165
166 exploded = bmake_malloc((size_t)(p - flags) * 3 + 1);
167 for (p = flags, ep = exploded; *p != '\0'; p++) {
168 *ep++ = '-';
169 *ep++ = *p;
170 *ep++ = ' ';
171 }
172 *ep = '\0';
173 return exploded;
174 }
175
176 MAKE_ATTR_DEAD static void
177 usage(void)
178 {
179 size_t prognameLen = strcspn(progname, "[");
180
181 (void)fprintf(stderr,
182 "usage: %.*s [-BeikNnqrSstWwX]\n"
183 " [-C directory] [-D variable] [-d flags] [-f makefile]\n"
184 " [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n"
185 " [-V variable] [-v variable] [variable=value] [target ...]\n",
186 (int)prognameLen, progname);
187 exit(2);
188 }
189
190 static void
191 MainParseArgDebugFile(const char *arg)
192 {
193 const char *mode;
194 size_t len;
195 char *fname;
196
197 if (opts.debug_file != stdout && opts.debug_file != stderr)
198 fclose(opts.debug_file);
199
200 if (*arg == '+') {
201 arg++;
202 mode = "a";
203 } else
204 mode = "w";
205
206 if (strcmp(arg, "stdout") == 0) {
207 opts.debug_file = stdout;
208 return;
209 }
210 if (strcmp(arg, "stderr") == 0) {
211 opts.debug_file = stderr;
212 return;
213 }
214
215 len = strlen(arg);
216 fname = bmake_malloc(len + 20);
217 memcpy(fname, arg, len + 1);
218
219 /* Replace the trailing '%d' after '.%d' with the pid. */
220 if (len >= 3 && memcmp(fname + len - 3, ".%d", 3) == 0)
221 snprintf(fname + len - 2, 20, "%d", getpid());
222
223 opts.debug_file = fopen(fname, mode);
224 if (opts.debug_file == NULL) {
225 fprintf(stderr, "Cannot open debug file \"%s\"\n",
226 fname);
227 exit(2);
228 }
229 free(fname);
230 }
231
232 static void
233 MainParseArgDebug(const char *argvalue)
234 {
235 const char *modules;
236 DebugFlags debug = opts.debug;
237
238 for (modules = argvalue; *modules != '\0'; modules++) {
239 switch (*modules) {
240 case '0': /* undocumented, only intended for tests */
241 memset(&debug, 0, sizeof(debug));
242 break;
243 case 'A':
244 memset(&debug, ~0, sizeof(debug));
245 break;
246 case 'a':
247 debug.DEBUG_ARCH = true;
248 break;
249 case 'C':
250 debug.DEBUG_CWD = true;
251 break;
252 case 'c':
253 debug.DEBUG_COND = true;
254 break;
255 case 'd':
256 debug.DEBUG_DIR = true;
257 break;
258 case 'e':
259 debug.DEBUG_ERROR = true;
260 break;
261 case 'f':
262 debug.DEBUG_FOR = true;
263 break;
264 case 'g':
265 if (modules[1] == '1') {
266 debug.DEBUG_GRAPH1 = true;
267 modules++;
268 } else if (modules[1] == '2') {
269 debug.DEBUG_GRAPH2 = true;
270 modules++;
271 } else if (modules[1] == '3') {
272 debug.DEBUG_GRAPH3 = true;
273 modules++;
274 }
275 break;
276 case 'h':
277 debug.DEBUG_HASH = true;
278 break;
279 case 'j':
280 debug.DEBUG_JOB = true;
281 break;
282 case 'L':
283 opts.strict = true;
284 break;
285 case 'l':
286 debug.DEBUG_LOUD = true;
287 break;
288 case 'M':
289 debug.DEBUG_META = true;
290 break;
291 case 'm':
292 debug.DEBUG_MAKE = true;
293 break;
294 case 'n':
295 debug.DEBUG_SCRIPT = true;
296 break;
297 case 'p':
298 debug.DEBUG_PARSE = true;
299 break;
300 case 's':
301 debug.DEBUG_SUFF = true;
302 break;
303 case 't':
304 debug.DEBUG_TARG = true;
305 break;
306 case 'V':
307 opts.debugVflag = true;
308 break;
309 case 'v':
310 debug.DEBUG_VAR = true;
311 break;
312 case 'x':
313 debug.DEBUG_SHELL = true;
314 break;
315 case 'F':
316 MainParseArgDebugFile(modules + 1);
317 goto debug_setbuf;
318 default:
319 (void)fprintf(stderr,
320 "%s: illegal argument to d option -- %c\n",
321 progname, *modules);
322 usage();
323 }
324 }
325
326 debug_setbuf:
327 opts.debug = debug;
328
329 /*
330 * Make the debug_file unbuffered, and make
331 * stdout line buffered (unless debugfile == stdout).
332 */
333 setvbuf(opts.debug_file, NULL, _IONBF, 0);
334 if (opts.debug_file != stdout) {
335 setvbuf(stdout, NULL, _IOLBF, 0);
336 }
337 }
338
339 /* Is path relative, or does it contain any relative component "." or ".."? */
340 static bool
341 IsRelativePath(const char *path)
342 {
343 const char *p;
344
345 if (path[0] != '/')
346 return true;
347 p = path;
348 while ((p = strstr(p, "/.")) != NULL) {
349 p += 2;
350 if (*p == '.')
351 p++;
352 if (*p == '/' || *p == '\0')
353 return true;
354 }
355 return false;
356 }
357
358 static void
359 MainParseArgChdir(const char *argvalue)
360 {
361 struct stat sa, sb;
362
363 if (chdir(argvalue) == -1) {
364 (void)fprintf(stderr, "%s: chdir %s: %s\n",
365 progname, argvalue, strerror(errno));
366 exit(2); /* Not 1 so -q can distinguish error */
367 }
368 if (getcwd(curdir, MAXPATHLEN) == NULL) {
369 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
370 exit(2);
371 }
372 if (!IsRelativePath(argvalue) &&
373 stat(argvalue, &sa) != -1 &&
374 stat(curdir, &sb) != -1 &&
375 sa.st_ino == sb.st_ino &&
376 sa.st_dev == sb.st_dev)
377 strncpy(curdir, argvalue, MAXPATHLEN);
378 ignorePWD = true;
379 }
380
381 static void
382 MainParseArgJobsInternal(const char *argvalue)
383 {
384 char end;
385 if (sscanf(argvalue, "%d,%d%c", &jp_0, &jp_1, &end) != 2) {
386 (void)fprintf(stderr,
387 "%s: internal error -- J option malformed (%s)\n",
388 progname, argvalue);
389 usage();
390 }
391 if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
392 (fcntl(jp_1, F_GETFD, 0) < 0)) {
393 jp_0 = -1;
394 jp_1 = -1;
395 opts.compatMake = true;
396 } else {
397 Global_Append(MAKEFLAGS, "-J");
398 Global_Append(MAKEFLAGS, argvalue);
399 }
400 }
401
402 static void
403 MainParseArgJobs(const char *argvalue)
404 {
405 char *p;
406
407 forceJobs = true;
408 opts.maxJobs = (int)strtol(argvalue, &p, 0);
409 if (*p != '\0' || opts.maxJobs < 1) {
410 (void)fprintf(stderr,
411 "%s: illegal argument to -j -- must be positive integer!\n",
412 progname);
413 exit(2); /* Not 1 so -q can distinguish error */
414 }
415 Global_Append(MAKEFLAGS, "-j");
416 Global_Append(MAKEFLAGS, argvalue);
417 Global_Set(".MAKE.JOBS", argvalue);
418 maxJobTokens = opts.maxJobs;
419 }
420
421 static void
422 MainParseArgSysInc(const char *argvalue)
423 {
424 /* look for magic parent directory search string */
425 if (strncmp(".../", argvalue, 4) == 0) {
426 char *found_path = Dir_FindHereOrAbove(curdir, argvalue + 4);
427 if (found_path == NULL)
428 return;
429 (void)SearchPath_Add(sysIncPath, found_path);
430 free(found_path);
431 } else {
432 (void)SearchPath_Add(sysIncPath, argvalue);
433 }
434 Global_Append(MAKEFLAGS, "-m");
435 Global_Append(MAKEFLAGS, argvalue);
436 }
437
438 static bool
439 MainParseArg(char c, const char *argvalue)
440 {
441 switch (c) {
442 case '\0':
443 break;
444 case 'B':
445 opts.compatMake = true;
446 Global_Append(MAKEFLAGS, "-B");
447 Global_Set(MAKE_MODE, "compat");
448 break;
449 case 'C':
450 MainParseArgChdir(argvalue);
451 break;
452 case 'D':
453 if (argvalue[0] == '\0')
454 return false;
455 Global_SetExpand(argvalue, "1");
456 Global_Append(MAKEFLAGS, "-D");
457 Global_Append(MAKEFLAGS, argvalue);
458 break;
459 case 'I':
460 Parse_AddIncludeDir(argvalue);
461 Global_Append(MAKEFLAGS, "-I");
462 Global_Append(MAKEFLAGS, argvalue);
463 break;
464 case 'J':
465 MainParseArgJobsInternal(argvalue);
466 break;
467 case 'N':
468 opts.noExecute = true;
469 opts.noRecursiveExecute = true;
470 Global_Append(MAKEFLAGS, "-N");
471 break;
472 case 'S':
473 opts.keepgoing = false;
474 Global_Append(MAKEFLAGS, "-S");
475 break;
476 case 'T':
477 tracefile = bmake_strdup(argvalue);
478 Global_Append(MAKEFLAGS, "-T");
479 Global_Append(MAKEFLAGS, argvalue);
480 break;
481 case 'V':
482 case 'v':
483 opts.printVars = c == 'v' ? PVM_EXPANDED : PVM_UNEXPANDED;
484 Lst_Append(&opts.variables, bmake_strdup(argvalue));
485 /* XXX: Why always -V? */
486 Global_Append(MAKEFLAGS, "-V");
487 Global_Append(MAKEFLAGS, argvalue);
488 break;
489 case 'W':
490 opts.parseWarnFatal = true;
491 /* XXX: why no Global_Append? */
492 break;
493 case 'X':
494 opts.varNoExportEnv = true;
495 Global_Append(MAKEFLAGS, "-X");
496 break;
497 case 'd':
498 /* If '-d-opts' don't pass to children */
499 if (argvalue[0] == '-')
500 argvalue++;
501 else {
502 Global_Append(MAKEFLAGS, "-d");
503 Global_Append(MAKEFLAGS, argvalue);
504 }
505 MainParseArgDebug(argvalue);
506 break;
507 case 'e':
508 opts.checkEnvFirst = true;
509 Global_Append(MAKEFLAGS, "-e");
510 break;
511 case 'f':
512 Lst_Append(&opts.makefiles, bmake_strdup(argvalue));
513 break;
514 case 'i':
515 opts.ignoreErrors = true;
516 Global_Append(MAKEFLAGS, "-i");
517 break;
518 case 'j':
519 MainParseArgJobs(argvalue);
520 break;
521 case 'k':
522 opts.keepgoing = true;
523 Global_Append(MAKEFLAGS, "-k");
524 break;
525 case 'm':
526 MainParseArgSysInc(argvalue);
527 /* XXX: why no Var_Append? */
528 break;
529 case 'n':
530 opts.noExecute = true;
531 Global_Append(MAKEFLAGS, "-n");
532 break;
533 case 'q':
534 opts.query = true;
535 /* Kind of nonsensical, wot? */
536 Global_Append(MAKEFLAGS, "-q");
537 break;
538 case 'r':
539 opts.noBuiltins = true;
540 Global_Append(MAKEFLAGS, "-r");
541 break;
542 case 's':
543 opts.silent = true;
544 Global_Append(MAKEFLAGS, "-s");
545 break;
546 case 't':
547 opts.touch = true;
548 Global_Append(MAKEFLAGS, "-t");
549 break;
550 case 'w':
551 opts.enterFlag = true;
552 Global_Append(MAKEFLAGS, "-w");
553 break;
554 default:
555 usage();
556 }
557 return true;
558 }
559
560 /*
561 * Parse the given arguments. Called from main() and from
562 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
563 *
564 * The arguments must be treated as read-only and will be freed after the
565 * call.
566 *
567 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
568 */
569 static void
570 MainParseArgs(int argc, char **argv)
571 {
572 char c;
573 int arginc;
574 char *argvalue;
575 char *optscan;
576 bool inOption, dashDash = false;
577
578 const char *optspecs = "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrstv:w";
579 /* Can't actually use getopt(3) because rescanning is not portable */
580
581 rearg:
582 inOption = false;
583 optscan = NULL;
584 while (argc > 1) {
585 const char *optspec;
586 if (!inOption)
587 optscan = argv[1];
588 c = *optscan++;
589 arginc = 0;
590 if (inOption) {
591 if (c == '\0') {
592 argv++;
593 argc--;
594 inOption = false;
595 continue;
596 }
597 } else {
598 if (c != '-' || dashDash)
599 break;
600 inOption = true;
601 c = *optscan++;
602 }
603 /* '-' found at some earlier point */
604 optspec = strchr(optspecs, c);
605 if (c != '\0' && optspec != NULL && optspec[1] == ':') {
606 /*
607 * -<something> found, and <something> should have an
608 * argument
609 */
610 inOption = false;
611 arginc = 1;
612 argvalue = optscan;
613 if (*argvalue == '\0') {
614 if (argc < 3)
615 goto noarg;
616 argvalue = argv[2];
617 arginc = 2;
618 }
619 } else {
620 argvalue = NULL;
621 }
622 switch (c) {
623 case '\0':
624 arginc = 1;
625 inOption = false;
626 break;
627 case '-':
628 dashDash = true;
629 break;
630 default:
631 if (!MainParseArg(c, argvalue))
632 goto noarg;
633 }
634 argv += arginc;
635 argc -= arginc;
636 }
637
638 /*
639 * See if the rest of the arguments are variable assignments and
640 * perform them if so. Else take them to be targets and stuff them
641 * on the end of the "create" list.
642 */
643 for (; argc > 1; argv++, argc--) {
644 if (!Parse_VarAssign(argv[1], false, SCOPE_CMDLINE)) {
645 if (argv[1][0] == '\0')
646 Punt("illegal (null) argument.");
647 if (argv[1][0] == '-' && !dashDash)
648 goto rearg;
649 Lst_Append(&opts.create, bmake_strdup(argv[1]));
650 }
651 }
652
653 return;
654 noarg:
655 (void)fprintf(stderr, "%s: option requires an argument -- %c\n",
656 progname, c);
657 usage();
658 }
659
660 /*
661 * Break a line of arguments into words and parse them.
662 *
663 * Used when a .MFLAGS or .MAKEFLAGS target is encountered during parsing and
664 * by main() when reading the MAKEFLAGS environment variable.
665 */
666 void
667 Main_ParseArgLine(const char *line)
668 {
669 Words words;
670 char *buf;
671
672 if (line == NULL)
673 return;
674 /* XXX: don't use line as an iterator variable */
675 for (; *line == ' '; line++)
676 continue;
677 if (line[0] == '\0')
678 return;
679
680 {
681 FStr argv0 = Var_Value(SCOPE_GLOBAL, ".MAKE");
682 buf = str_concat3(argv0.str, " ", line);
683 FStr_Done(&argv0);
684 }
685
686 words = Str_Words(buf, true);
687 if (words.words == NULL) {
688 Error("Unterminated quoted string [%s]", buf);
689 free(buf);
690 return;
691 }
692 free(buf);
693 MainParseArgs((int)words.len, words.words);
694
695 Words_Free(words);
696 }
697
698 bool
699 Main_SetObjdir(bool writable, const char *fmt, ...)
700 {
701 struct stat sb;
702 char *path;
703 char buf[MAXPATHLEN + 1];
704 char buf2[MAXPATHLEN + 1];
705 va_list ap;
706
707 va_start(ap, fmt);
708 vsnprintf(path = buf, MAXPATHLEN, fmt, ap);
709 va_end(ap);
710
711 if (path[0] != '/') {
712 snprintf(buf2, MAXPATHLEN, "%s/%s", curdir, path);
713 path = buf2;
714 }
715
716 /* look for the directory and try to chdir there */
717 if (stat(path, &sb) != 0 || !S_ISDIR(sb.st_mode))
718 return false;
719
720 if ((writable && access(path, W_OK) != 0) || chdir(path) != 0) {
721 (void)fprintf(stderr, "%s warning: %s: %s.\n",
722 progname, path, strerror(errno));
723 return false;
724 }
725
726 snprintf(objdir, sizeof objdir, "%s", path);
727 Global_Set(".OBJDIR", objdir);
728 setenv("PWD", objdir, 1);
729 Dir_InitDot();
730 purge_relative_cached_realpaths();
731 if (opts.enterFlag && strcmp(objdir, curdir) != 0)
732 enterFlagObj = true;
733 return true;
734 }
735
736 static bool
737 SetVarObjdir(bool writable, const char *var, const char *suffix)
738 {
739 FStr path = Var_Value(SCOPE_CMDLINE, var);
740
741 if (path.str == NULL || path.str[0] == '\0') {
742 FStr_Done(&path);
743 return false;
744 }
745
746 /* expand variable substitutions */
747 if (strchr(path.str, '$') != 0) {
748 char *expanded;
749 (void)Var_Subst(path.str, SCOPE_GLOBAL, VARE_WANTRES, &expanded);
750 /* TODO: handle errors */
751 FStr_Done(&path);
752 path = FStr_InitOwn(expanded);
753 }
754
755 (void)Main_SetObjdir(writable, "%s%s", path.str, suffix);
756
757 FStr_Done(&path);
758 return true;
759 }
760
761 /*
762 * Splits str into words, adding them to the list.
763 * The string must be kept alive as long as the list.
764 */
765 int
766 str2Lst_Append(StringList *lp, char *str)
767 {
768 char *cp;
769 int n;
770
771 const char *sep = " \t";
772
773 for (n = 0, cp = strtok(str, sep); cp != NULL; cp = strtok(NULL, sep)) {
774 Lst_Append(lp, cp);
775 n++;
776 }
777 return n;
778 }
779
780 #ifdef SIGINFO
781 /*ARGSUSED*/
782 static void
783 siginfo(int signo MAKE_ATTR_UNUSED)
784 {
785 char dir[MAXPATHLEN];
786 char str[2 * MAXPATHLEN];
787 int len;
788 if (getcwd(dir, sizeof dir) == NULL)
789 return;
790 len = snprintf(str, sizeof str, "%s: Working in: %s\n", progname, dir);
791 if (len > 0)
792 (void)write(STDERR_FILENO, str, (size_t)len);
793 }
794 #endif
795
796 /* Allow makefiles some control over the mode we run in. */
797 static void
798 MakeMode(void)
799 {
800 char *mode;
801
802 (void)Var_Subst("${" MAKE_MODE ":tl}", SCOPE_GLOBAL, VARE_WANTRES, &mode);
803 /* TODO: handle errors */
804
805 if (mode[0] != '\0') {
806 if (strstr(mode, "compat") != NULL) {
807 opts.compatMake = true;
808 forceJobs = false;
809 }
810 #if USE_META
811 if (strstr(mode, "meta") != NULL)
812 meta_mode_init(mode);
813 #endif
814 }
815
816 free(mode);
817 }
818
819 static void
820 PrintVar(const char *varname, bool expandVars)
821 {
822 if (strchr(varname, '$') != NULL) {
823 char *evalue;
824 (void)Var_Subst(varname, SCOPE_GLOBAL, VARE_WANTRES, &evalue);
825 /* TODO: handle errors */
826 printf("%s\n", evalue);
827 free(evalue);
828
829 } else if (expandVars) {
830 char *expr = str_concat3("${", varname, "}");
831 char *evalue;
832 (void)Var_Subst(expr, SCOPE_GLOBAL, VARE_WANTRES, &evalue);
833 /* TODO: handle errors */
834 free(expr);
835 printf("%s\n", evalue);
836 free(evalue);
837
838 } else {
839 FStr value = Var_Value(SCOPE_GLOBAL, varname);
840 printf("%s\n", value.str != NULL ? value.str : "");
841 FStr_Done(&value);
842 }
843 }
844
845 /*
846 * Return a bool based on a variable.
847 *
848 * If the knob is not set, return the fallback.
849 * If set, anything that looks or smells like "No", "False", "Off", "0", etc.
850 * is false, otherwise true.
851 */
852 static bool
853 GetBooleanExpr(const char *expr, bool fallback)
854 {
855 char *value;
856 bool res;
857
858 (void)Var_Subst(expr, SCOPE_GLOBAL, VARE_WANTRES, &value);
859 /* TODO: handle errors */
860 res = ParseBoolean(value, fallback);
861 free(value);
862 return res;
863 }
864
865 static void
866 doPrintVars(void)
867 {
868 StringListNode *ln;
869 bool expandVars;
870
871 if (opts.printVars == PVM_EXPANDED)
872 expandVars = true;
873 else if (opts.debugVflag)
874 expandVars = false;
875 else
876 expandVars = GetBooleanExpr("${.MAKE.EXPAND_VARIABLES}",
877 false);
878
879 for (ln = opts.variables.first; ln != NULL; ln = ln->next) {
880 const char *varname = ln->datum;
881 PrintVar(varname, expandVars);
882 }
883 }
884
885 static bool
886 runTargets(void)
887 {
888 GNodeList targs = LST_INIT; /* target nodes to create */
889 bool outOfDate; /* false if all targets up to date */
890
891 /*
892 * Have now read the entire graph and need to make a list of
893 * targets to create. If none was given on the command line,
894 * we consult the parsing module to find the main target(s)
895 * to create.
896 */
897 if (Lst_IsEmpty(&opts.create))
898 Parse_MainName(&targs);
899 else
900 Targ_FindList(&targs, &opts.create);
901
902 if (!opts.compatMake) {
903 /*
904 * Initialize job module before traversing the graph
905 * now that any .BEGIN and .END targets have been read.
906 * This is done only if the -q flag wasn't given
907 * (to prevent the .BEGIN from being executed should
908 * it exist).
909 */
910 if (!opts.query) {
911 Job_Init();
912 jobsRunning = true;
913 }
914
915 /* Traverse the graph, checking on all the targets */
916 outOfDate = Make_Run(&targs);
917 } else {
918 /*
919 * Compat_Init will take care of creating all the
920 * targets as well as initializing the module.
921 */
922 Compat_Run(&targs);
923 outOfDate = false;
924 }
925 Lst_Done(&targs); /* Don't free the targets themselves. */
926 return outOfDate;
927 }
928
929 /*
930 * Set up the .TARGETS variable to contain the list of targets to be
931 * created. If none specified, make the variable empty -- the parser
932 * will fill the thing in with the default or .MAIN target.
933 */
934 static void
935 InitVarTargets(void)
936 {
937 StringListNode *ln;
938
939 if (Lst_IsEmpty(&opts.create)) {
940 Global_Set(".TARGETS", "");
941 return;
942 }
943
944 for (ln = opts.create.first; ln != NULL; ln = ln->next) {
945 const char *name = ln->datum;
946 Global_Append(".TARGETS", name);
947 }
948 }
949
950 static void
951 InitRandom(void)
952 {
953 struct timeval tv;
954
955 gettimeofday(&tv, NULL);
956 srandom((unsigned int)(tv.tv_sec + tv.tv_usec));
957 }
958
959 static const char *
960 InitVarMachine(const struct utsname *utsname MAKE_ATTR_UNUSED)
961 {
962 const char *machine = getenv("MACHINE");
963 if (machine != NULL)
964 return machine;
965
966 #if defined(MAKE_NATIVE)
967 return utsname->machine;
968 #elif defined(MAKE_MACHINE)
969 return MAKE_MACHINE;
970 #else
971 return "unknown";
972 #endif
973 }
974
975 static const char *
976 InitVarMachineArch(void)
977 {
978 const char *env = getenv("MACHINE_ARCH");
979 if (env != NULL)
980 return env;
981
982 #ifdef MAKE_NATIVE
983 {
984 struct utsname utsname;
985 static char machine_arch_buf[sizeof utsname.machine];
986 const int mib[2] = { CTL_HW, HW_MACHINE_ARCH };
987 size_t len = sizeof machine_arch_buf;
988
989 if (sysctl(mib, (unsigned int)__arraycount(mib),
990 machine_arch_buf, &len, NULL, 0) < 0) {
991 (void)fprintf(stderr, "%s: sysctl failed (%s).\n",
992 progname, strerror(errno));
993 exit(2);
994 }
995
996 return machine_arch_buf;
997 }
998 #elif defined(MACHINE_ARCH)
999 return MACHINE_ARCH;
1000 #elif defined(MAKE_MACHINE_ARCH)
1001 return MAKE_MACHINE_ARCH;
1002 #else
1003 return "unknown";
1004 #endif
1005 }
1006
1007 #ifndef NO_PWD_OVERRIDE
1008 /*
1009 * All this code is so that we know where we are when we start up
1010 * on a different machine with pmake.
1011 *
1012 * XXX: Make no longer has "local" and "remote" mode. Is this code still
1013 * necessary?
1014 *
1015 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
1016 * since the value of curdir can vary depending on how we got
1017 * here. Ie sitting at a shell prompt (shell that provides $PWD)
1018 * or via subdir.mk in which case its likely a shell which does
1019 * not provide it.
1020 *
1021 * So, to stop it breaking this case only, we ignore PWD if
1022 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a variable expression.
1023 */
1024 static void
1025 HandlePWD(const struct stat *curdir_st)
1026 {
1027 char *pwd;
1028 FStr prefix, makeobjdir;
1029 struct stat pwd_st;
1030
1031 if (ignorePWD || (pwd = getenv("PWD")) == NULL)
1032 return;
1033
1034 prefix = Var_Value(SCOPE_CMDLINE, "MAKEOBJDIRPREFIX");
1035 if (prefix.str != NULL) {
1036 FStr_Done(&prefix);
1037 return;
1038 }
1039
1040 makeobjdir = Var_Value(SCOPE_CMDLINE, "MAKEOBJDIR");
1041 if (makeobjdir.str != NULL && strchr(makeobjdir.str, '$') != NULL)
1042 goto ignore_pwd;
1043
1044 if (stat(pwd, &pwd_st) == 0 &&
1045 curdir_st->st_ino == pwd_st.st_ino &&
1046 curdir_st->st_dev == pwd_st.st_dev)
1047 (void)strncpy(curdir, pwd, MAXPATHLEN);
1048
1049 ignore_pwd:
1050 FStr_Done(&makeobjdir);
1051 }
1052 #endif
1053
1054 /*
1055 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that, MAKEOBJDIR is set
1056 * in the environment, try only that value and fall back to .CURDIR if it
1057 * does not exist.
1058 *
1059 * Otherwise, try _PATH_OBJDIR.MACHINE-MACHINE_ARCH, _PATH_OBJDIR.MACHINE,
1060 * and finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none of these
1061 * paths exist, just use .CURDIR.
1062 */
1063 static void
1064 InitObjdir(const char *machine, const char *machine_arch)
1065 {
1066 bool writable;
1067
1068 Dir_InitCur(curdir);
1069 writable = GetBooleanExpr("${MAKE_OBJDIR_CHECK_WRITABLE}", true);
1070 (void)Main_SetObjdir(false, "%s", curdir);
1071
1072 if (!SetVarObjdir(writable, "MAKEOBJDIRPREFIX", curdir) &&
1073 !SetVarObjdir(writable, "MAKEOBJDIR", "") &&
1074 !Main_SetObjdir(writable, "%s.%s-%s", _PATH_OBJDIR, machine, machine_arch) &&
1075 !Main_SetObjdir(writable, "%s.%s", _PATH_OBJDIR, machine) &&
1076 !Main_SetObjdir(writable, "%s", _PATH_OBJDIR))
1077 (void)Main_SetObjdir(writable, "%s%s", _PATH_OBJDIRPREFIX, curdir);
1078 }
1079
1080 /* get rid of resource limit on file descriptors */
1081 static void
1082 UnlimitFiles(void)
1083 {
1084 #if defined(MAKE_NATIVE) || (defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE))
1085 struct rlimit rl;
1086 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
1087 rl.rlim_cur != rl.rlim_max) {
1088 rl.rlim_cur = rl.rlim_max;
1089 (void)setrlimit(RLIMIT_NOFILE, &rl);
1090 }
1091 #endif
1092 }
1093
1094 static void
1095 CmdOpts_Init(void)
1096 {
1097 opts.compatMake = false;
1098 memset(&opts.debug, 0, sizeof(opts.debug));
1099 /* opts.debug_file has already been initialized earlier */
1100 opts.strict = false;
1101 opts.debugVflag = false;
1102 opts.checkEnvFirst = false;
1103 Lst_Init(&opts.makefiles);
1104 opts.ignoreErrors = false; /* Pay attention to non-zero returns */
1105 opts.maxJobs = 1;
1106 opts.keepgoing = false; /* Stop on error */
1107 opts.noRecursiveExecute = false; /* Execute all .MAKE targets */
1108 opts.noExecute = false; /* Execute all commands */
1109 opts.query = false;
1110 opts.noBuiltins = false; /* Read the built-in rules */
1111 opts.silent = false; /* Print commands as executed */
1112 opts.touch = false;
1113 opts.printVars = PVM_NONE;
1114 Lst_Init(&opts.variables);
1115 opts.parseWarnFatal = false;
1116 opts.enterFlag = false;
1117 opts.varNoExportEnv = false;
1118 Lst_Init(&opts.create);
1119 }
1120
1121 /*
1122 * Initialize MAKE and .MAKE to the path of the executable, so that it can be
1123 * found by execvp(3) and the shells, even after a chdir.
1124 *
1125 * If it's a relative path and contains a '/', resolve it to an absolute path.
1126 * Otherwise keep it as is, assuming it will be found in the PATH.
1127 */
1128 static void
1129 InitVarMake(const char *argv0)
1130 {
1131 const char *make = argv0;
1132
1133 if (argv0[0] != '/' && strchr(argv0, '/') != NULL) {
1134 char pathbuf[MAXPATHLEN];
1135 const char *abspath = cached_realpath(argv0, pathbuf);
1136 struct stat st;
1137 if (abspath != NULL && abspath[0] == '/' &&
1138 stat(make, &st) == 0)
1139 make = abspath;
1140 }
1141
1142 Global_Set("MAKE", make);
1143 Global_Set(".MAKE", make);
1144 }
1145
1146 /*
1147 * Add the directories from the colon-separated syspath to defSysIncPath.
1148 * After returning, the contents of syspath is unspecified.
1149 */
1150 static void
1151 InitDefSysIncPath(char *syspath)
1152 {
1153 static char defsyspath[] = _PATH_DEFSYSPATH;
1154 char *start, *cp;
1155
1156 /*
1157 * If no user-supplied system path was given (through the -m option)
1158 * add the directories from the DEFSYSPATH (more than one may be given
1159 * as dir1:...:dirn) to the system include path.
1160 */
1161 if (syspath == NULL || syspath[0] == '\0')
1162 syspath = defsyspath;
1163 else
1164 syspath = bmake_strdup(syspath);
1165
1166 for (start = syspath; *start != '\0'; start = cp) {
1167 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1168 continue;
1169 if (*cp == ':')
1170 *cp++ = '\0';
1171
1172 /* look for magic parent directory search string */
1173 if (strncmp(start, ".../", 4) == 0) {
1174 char *dir = Dir_FindHereOrAbove(curdir, start + 4);
1175 if (dir != NULL) {
1176 (void)SearchPath_Add(defSysIncPath, dir);
1177 free(dir);
1178 }
1179 } else {
1180 (void)SearchPath_Add(defSysIncPath, start);
1181 }
1182 }
1183
1184 if (syspath != defsyspath)
1185 free(syspath);
1186 }
1187
1188 static void
1189 ReadBuiltinRules(void)
1190 {
1191 StringListNode *ln;
1192 StringList sysMkFiles = LST_INIT;
1193
1194 SearchPath_Expand(
1195 Lst_IsEmpty(&sysIncPath->dirs) ? defSysIncPath : sysIncPath,
1196 _PATH_DEFSYSMK,
1197 &sysMkFiles);
1198 if (Lst_IsEmpty(&sysMkFiles))
1199 Fatal("%s: no system rules (%s).", progname, _PATH_DEFSYSMK);
1200
1201 for (ln = sysMkFiles.first; ln != NULL; ln = ln->next)
1202 if (ReadMakefile(ln->datum))
1203 break;
1204
1205 if (ln == NULL)
1206 Fatal("%s: cannot open %s.",
1207 progname, (const char *)sysMkFiles.first->datum);
1208
1209 Lst_DoneCall(&sysMkFiles, free);
1210 }
1211
1212 static void
1213 InitMaxJobs(void)
1214 {
1215 char *value;
1216 int n;
1217
1218 if (forceJobs || opts.compatMake ||
1219 !Var_Exists(SCOPE_GLOBAL, ".MAKE.JOBS"))
1220 return;
1221
1222 (void)Var_Subst("${.MAKE.JOBS}", SCOPE_GLOBAL, VARE_WANTRES, &value);
1223 /* TODO: handle errors */
1224 n = (int)strtol(value, NULL, 0);
1225 if (n < 1) {
1226 (void)fprintf(stderr,
1227 "%s: illegal value for .MAKE.JOBS "
1228 "-- must be positive integer!\n",
1229 progname);
1230 exit(2); /* Not 1 so -q can distinguish error */
1231 }
1232
1233 if (n != opts.maxJobs) {
1234 Global_Append(MAKEFLAGS, "-j");
1235 Global_Append(MAKEFLAGS, value);
1236 }
1237
1238 opts.maxJobs = n;
1239 maxJobTokens = opts.maxJobs;
1240 forceJobs = true;
1241 free(value);
1242 }
1243
1244 /*
1245 * For compatibility, look at the directories in the VPATH variable
1246 * and add them to the search path, if the variable is defined. The
1247 * variable's value is in the same format as the PATH environment
1248 * variable, i.e. <directory>:<directory>:<directory>...
1249 */
1250 static void
1251 InitVpath(void)
1252 {
1253 char *vpath, savec, *path;
1254 if (!Var_Exists(SCOPE_CMDLINE, "VPATH"))
1255 return;
1256
1257 (void)Var_Subst("${VPATH}", SCOPE_CMDLINE, VARE_WANTRES, &vpath);
1258 /* TODO: handle errors */
1259 path = vpath;
1260 do {
1261 char *cp;
1262 /* skip to end of directory */
1263 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1264 continue;
1265 /* Save terminator character so know when to stop */
1266 savec = *cp;
1267 *cp = '\0';
1268 /* Add directory to search path */
1269 (void)SearchPath_Add(&dirSearchPath, path);
1270 *cp = savec;
1271 path = cp + 1;
1272 } while (savec == ':');
1273 free(vpath);
1274 }
1275
1276 static void
1277 ReadAllMakefiles(const StringList *makefiles)
1278 {
1279 StringListNode *ln;
1280
1281 for (ln = makefiles->first; ln != NULL; ln = ln->next) {
1282 const char *fname = ln->datum;
1283 if (!ReadMakefile(fname))
1284 Fatal("%s: cannot open %s.", progname, fname);
1285 }
1286 }
1287
1288 static void
1289 ReadFirstDefaultMakefile(void)
1290 {
1291 StringList makefiles = LST_INIT;
1292 StringListNode *ln;
1293 char *prefs;
1294
1295 (void)Var_Subst("${" MAKE_MAKEFILE_PREFERENCE "}",
1296 SCOPE_CMDLINE, VARE_WANTRES, &prefs);
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(".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(".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(".MAKE.PID", buf);
1416 snprintf(buf, sizeof buf, "%u", getppid());
1417 Global_Set(".MAKE.PPID", buf);
1418 snprintf(buf, sizeof buf, "%u", getuid());
1419 Global_Set(".MAKE.UID", buf);
1420 snprintf(buf, sizeof buf, "%u", getgid());
1421 Global_Set(".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 (!opts.noBuiltins)
1496 ReadBuiltinRules();
1497
1498 if (!Lst_IsEmpty(&opts.makefiles))
1499 ReadAllMakefiles(&opts.makefiles);
1500 else
1501 ReadFirstDefaultMakefile();
1502 }
1503
1504 /* Compute the dependency graph. */
1505 static void
1506 main_PrepareMaking(void)
1507 {
1508 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1509 if (!opts.noBuiltins || opts.printVars == PVM_NONE) {
1510 (void)Var_Subst("${.MAKE.DEPENDFILE}",
1511 SCOPE_CMDLINE, VARE_WANTRES, &makeDependfile);
1512 if (makeDependfile[0] != '\0') {
1513 /* TODO: handle errors */
1514 doing_depend = true;
1515 (void)ReadMakefile(makeDependfile);
1516 doing_depend = false;
1517 }
1518 }
1519
1520 if (enterFlagObj)
1521 printf("%s: Entering directory `%s'\n", progname, objdir);
1522
1523 MakeMode();
1524
1525 {
1526 FStr makeflags = Var_Value(SCOPE_GLOBAL, MAKEFLAGS);
1527 Global_Append("MFLAGS", makeflags.str);
1528 FStr_Done(&makeflags);
1529 }
1530
1531 InitMaxJobs();
1532
1533 if (!opts.compatMake && !forceJobs)
1534 opts.compatMake = true;
1535
1536 if (!opts.compatMake)
1537 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1538 DEBUG5(JOB, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1539 jp_0, jp_1, opts.maxJobs, maxJobTokens, opts.compatMake ? 1 : 0);
1540
1541 if (opts.printVars == PVM_NONE)
1542 Main_ExportMAKEFLAGS(true); /* initial export */
1543
1544 InitVpath();
1545
1546 /*
1547 * Now that all search paths have been read for suffixes et al, it's
1548 * time to add the default search path to their lists...
1549 */
1550 Suff_ExtendPaths();
1551
1552 /*
1553 * Propagate attributes through :: dependency lists.
1554 */
1555 Targ_Propagate();
1556
1557 /* print the initial graph, if the user requested it */
1558 if (DEBUG(GRAPH1))
1559 Targ_PrintGraph(1);
1560 }
1561
1562 /*
1563 * Make the targets.
1564 * If the -v or -V options are given, print variables instead.
1565 * Return whether any of the targets is out-of-date.
1566 */
1567 static bool
1568 main_Run(void)
1569 {
1570 if (opts.printVars != PVM_NONE) {
1571 /* print the values of any variables requested by the user */
1572 doPrintVars();
1573 return false;
1574 } else {
1575 return runTargets();
1576 }
1577 }
1578
1579 /* Clean up after making the targets. */
1580 static void
1581 main_CleanUp(void)
1582 {
1583 #ifdef CLEANUP
1584 Lst_DoneCall(&opts.variables, free);
1585 Lst_DoneCall(&opts.makefiles, free);
1586 Lst_DoneCall(&opts.create, free);
1587 #endif
1588
1589 if (DEBUG(GRAPH2))
1590 Targ_PrintGraph(2);
1591
1592 Trace_Log(MAKEEND, NULL);
1593
1594 if (enterFlagObj)
1595 printf("%s: Leaving directory `%s'\n", progname, objdir);
1596 if (opts.enterFlag)
1597 printf("%s: Leaving directory `%s'\n", progname, curdir);
1598
1599 #ifdef USE_META
1600 meta_finish();
1601 #endif
1602 Suff_End();
1603 Targ_End();
1604 Arch_End();
1605 Var_End();
1606 Parse_End();
1607 Dir_End();
1608 Job_End();
1609 Trace_End();
1610 Str_Intern_End();
1611 }
1612
1613 /* Determine the exit code. */
1614 static int
1615 main_Exit(bool outOfDate)
1616 {
1617 if (opts.strict && (main_errors > 0 || Parse_NumErrors() > 0))
1618 return 2; /* Not 1 so -q can distinguish error */
1619 return outOfDate ? 1 : 0;
1620 }
1621
1622 int
1623 main(int argc, char **argv)
1624 {
1625 bool outOfDate;
1626
1627 main_Init(argc, argv);
1628 main_ReadFiles();
1629 main_PrepareMaking();
1630 outOfDate = main_Run();
1631 main_CleanUp();
1632 return main_Exit(outOfDate);
1633 }
1634
1635 /*
1636 * Open and parse the given makefile, with all its side effects.
1637 * Return false if the file could not be opened.
1638 */
1639 static bool
1640 ReadMakefile(const char *fname)
1641 {
1642 int fd;
1643 char *name, *path = NULL;
1644
1645 if (strcmp(fname, "-") == 0) {
1646 Parse_File("(stdin)", -1);
1647 Var_Set(SCOPE_INTERNAL, "MAKEFILE", "");
1648 } else {
1649 /* if we've chdir'd, rebuild the path name */
1650 if (strcmp(curdir, objdir) != 0 && *fname != '/') {
1651 path = str_concat3(curdir, "/", fname);
1652 fd = open(path, O_RDONLY);
1653 if (fd != -1) {
1654 fname = path;
1655 goto found;
1656 }
1657 free(path);
1658
1659 /* If curdir failed, try objdir (ala .depend) */
1660 path = str_concat3(objdir, "/", fname);
1661 fd = open(path, O_RDONLY);
1662 if (fd != -1) {
1663 fname = path;
1664 goto found;
1665 }
1666 } else {
1667 fd = open(fname, O_RDONLY);
1668 if (fd != -1)
1669 goto found;
1670 }
1671 /* look in -I and system include directories. */
1672 name = Dir_FindFile(fname, parseIncPath);
1673 if (name == NULL) {
1674 SearchPath *sysInc = Lst_IsEmpty(&sysIncPath->dirs)
1675 ? defSysIncPath : sysIncPath;
1676 name = Dir_FindFile(fname, sysInc);
1677 }
1678 if (name == NULL || (fd = open(name, O_RDONLY)) == -1) {
1679 free(name);
1680 free(path);
1681 return false;
1682 }
1683 fname = name;
1684 /*
1685 * set the MAKEFILE variable desired by System V fans -- the
1686 * placement of the setting here means it gets set to the last
1687 * makefile specified, as it is set by SysV make.
1688 */
1689 found:
1690 if (!doing_depend)
1691 Var_Set(SCOPE_INTERNAL, "MAKEFILE", fname);
1692 Parse_File(fname, fd);
1693 }
1694 free(path);
1695 return true;
1696 }
1697
1698 /*
1699 * Execute the command in cmd, and return its output (only stdout, not
1700 * stderr). In the output, replace newlines with spaces.
1701 *
1702 * Results:
1703 * The output of the command, can be empty.
1704 * *errfmt returns a format string describing the command failure,
1705 * if any, using a single %s conversion specification.
1706 * TODO: replace errfmt with an actual error message.
1707 */
1708 char *
1709 Cmd_Exec(const char *cmd, const char **errfmt)
1710 {
1711 const char *args[4]; /* Arguments for invoking the shell */
1712 int pipefds[2];
1713 int cpid; /* Child PID */
1714 int pid; /* PID from wait() */
1715 int status; /* command exit status */
1716 Buffer buf; /* buffer to store the result */
1717 ssize_t bytes_read;
1718 char *res; /* result */
1719 char *cp;
1720 int saved_errno;
1721
1722 *errfmt = NULL;
1723
1724 if (shellName == NULL)
1725 Shell_Init();
1726
1727 args[0] = shellName;
1728 args[1] = "-c";
1729 args[2] = cmd;
1730 args[3] = NULL;
1731
1732 if (pipe(pipefds) == -1) {
1733 *errfmt = "Couldn't create pipe for \"%s\"";
1734 return bmake_strdup("");
1735 }
1736
1737 Var_ReexportVars();
1738
1739 switch (cpid = vfork()) {
1740 case 0:
1741 (void)close(pipefds[0]);
1742 (void)dup2(pipefds[1], STDOUT_FILENO);
1743 (void)close(pipefds[1]);
1744
1745 (void)execv(shellPath, UNCONST(args));
1746 _exit(1);
1747 /* NOTREACHED */
1748
1749 case -1:
1750 *errfmt = "Couldn't exec \"%s\"";
1751 return bmake_strdup("");
1752 }
1753
1754 (void)close(pipefds[1]); /* No need for the writing half */
1755
1756 saved_errno = 0;
1757 Buf_Init(&buf);
1758
1759 do {
1760 char result[BUFSIZ];
1761 bytes_read = read(pipefds[0], result, sizeof result);
1762 if (bytes_read > 0)
1763 Buf_AddBytes(&buf, result, (size_t)bytes_read);
1764 } while (bytes_read > 0 || (bytes_read == -1 && errno == EINTR));
1765 if (bytes_read == -1)
1766 saved_errno = errno;
1767
1768 (void)close(pipefds[0]); /* Close the input side of the pipe. */
1769
1770 while ((pid = waitpid(cpid, &status, 0)) != cpid && pid >= 0)
1771 JobReapChild(pid, status, false);
1772
1773 if (Buf_EndsWith(&buf, '\n'))
1774 buf.data[buf.len - 1] = '\0';
1775 res = Buf_DoneData(&buf);
1776
1777 for (cp = res; *cp != '\0'; cp++)
1778 if (*cp == '\n')
1779 *cp = ' ';
1780
1781 if (WIFSIGNALED(status))
1782 *errfmt = "\"%s\" exited on a signal";
1783 else if (WEXITSTATUS(status) != 0)
1784 *errfmt = "\"%s\" returned non-zero status";
1785 else if (saved_errno != 0)
1786 *errfmt = "Couldn't read shell's output for \"%s\"";
1787
1788 return res;
1789 }
1790
1791 /*
1792 * Print a printf-style error message.
1793 *
1794 * In default mode, this error message has no consequences, for compatibility
1795 * reasons, in particular it does not affect the exit status. Only in lint
1796 * mode (-dL) it does.
1797 */
1798 void
1799 Error(const char *fmt, ...)
1800 {
1801 va_list ap;
1802 FILE *err_file;
1803
1804 err_file = opts.debug_file;
1805 if (err_file == stdout)
1806 err_file = stderr;
1807 (void)fflush(stdout);
1808 for (;;) {
1809 va_start(ap, fmt);
1810 fprintf(err_file, "%s: ", progname);
1811 (void)vfprintf(err_file, fmt, ap);
1812 va_end(ap);
1813 (void)fprintf(err_file, "\n");
1814 (void)fflush(err_file);
1815 if (err_file == stderr)
1816 break;
1817 err_file = stderr;
1818 }
1819 main_errors++;
1820 }
1821
1822 /*
1823 * Wait for any running jobs to finish, then produce an error message,
1824 * finally exit immediately.
1825 *
1826 * Exiting immediately differs from Parse_Error, which exits only after the
1827 * current top-level makefile has been parsed completely.
1828 */
1829 void
1830 Fatal(const char *fmt, ...)
1831 {
1832 va_list ap;
1833
1834 if (jobsRunning)
1835 Job_Wait();
1836
1837 (void)fflush(stdout);
1838 va_start(ap, fmt);
1839 (void)vfprintf(stderr, fmt, ap);
1840 va_end(ap);
1841 (void)fprintf(stderr, "\n");
1842 (void)fflush(stderr);
1843
1844 PrintOnError(NULL, NULL);
1845
1846 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1847 Targ_PrintGraph(2);
1848 Trace_Log(MAKEERROR, NULL);
1849 exit(2); /* Not 1 so -q can distinguish error */
1850 }
1851
1852 /*
1853 * Major exception once jobs are being created.
1854 * Kills all jobs, prints a message and exits.
1855 */
1856 void
1857 Punt(const char *fmt, ...)
1858 {
1859 va_list ap;
1860
1861 va_start(ap, fmt);
1862 (void)fflush(stdout);
1863 (void)fprintf(stderr, "%s: ", progname);
1864 (void)vfprintf(stderr, fmt, ap);
1865 va_end(ap);
1866 (void)fprintf(stderr, "\n");
1867 (void)fflush(stderr);
1868
1869 PrintOnError(NULL, NULL);
1870
1871 DieHorribly();
1872 }
1873
1874 /* Exit without giving a message. */
1875 void
1876 DieHorribly(void)
1877 {
1878 if (jobsRunning)
1879 Job_AbortAll();
1880 if (DEBUG(GRAPH2))
1881 Targ_PrintGraph(2);
1882 Trace_Log(MAKEERROR, NULL);
1883 exit(2); /* Not 1 so -q can distinguish error */
1884 }
1885
1886 /*
1887 * Called when aborting due to errors in child shell to signal abnormal exit.
1888 * The program exits.
1889 * Errors is the number of errors encountered in Make_Make.
1890 */
1891 void
1892 Finish(int errs)
1893 {
1894 if (shouldDieQuietly(NULL, -1))
1895 exit(2);
1896 Fatal("%d error%s", errs, errs == 1 ? "" : "s");
1897 }
1898
1899 bool
1900 unlink_file(const char *file)
1901 {
1902 struct stat st;
1903
1904 if (lstat(file, &st) == -1)
1905 return false;
1906
1907 if (S_ISDIR(st.st_mode)) {
1908 errno = EISDIR;
1909 return false;
1910 }
1911 return unlink(file) == 0;
1912 }
1913
1914 static void
1915 write_all(int fd, const void *data, size_t n)
1916 {
1917 const char *mem = data;
1918
1919 while (n > 0) {
1920 ssize_t written = write(fd, mem, n);
1921 /* XXX: Should this EAGAIN be EINTR? */
1922 if (written == -1 && errno == EAGAIN)
1923 continue;
1924 if (written == -1)
1925 break;
1926 mem += written;
1927 n -= (size_t)written;
1928 }
1929 }
1930
1931 /* Print why exec failed, avoiding stdio. */
1932 void MAKE_ATTR_DEAD
1933 execDie(const char *af, const char *av)
1934 {
1935 Buffer buf;
1936
1937 Buf_Init(&buf);
1938 Buf_AddStr(&buf, progname);
1939 Buf_AddStr(&buf, ": ");
1940 Buf_AddStr(&buf, af);
1941 Buf_AddStr(&buf, "(");
1942 Buf_AddStr(&buf, av);
1943 Buf_AddStr(&buf, ") failed (");
1944 Buf_AddStr(&buf, strerror(errno));
1945 Buf_AddStr(&buf, ")\n");
1946
1947 write_all(STDERR_FILENO, buf.data, buf.len);
1948
1949 Buf_Done(&buf);
1950 _exit(1);
1951 }
1952
1953 static void
1954 purge_relative_cached_realpaths(void)
1955 {
1956 HashEntry *he, *nhe;
1957 HashIter hi;
1958
1959 HashIter_Init(&hi, &cached_realpaths);
1960 he = HashIter_Next(&hi);
1961 while (he != NULL) {
1962 nhe = HashIter_Next(&hi);
1963 if (he->key[0] != '/') {
1964 DEBUG1(DIR, "cached_realpath: purging %s\n", he->key);
1965 HashTable_DeleteEntry(&cached_realpaths, he);
1966 /*
1967 * XXX: What about the allocated he->value? Either
1968 * free them or document why they cannot be freed.
1969 */
1970 }
1971 he = nhe;
1972 }
1973 }
1974
1975 const char *
1976 cached_realpath(const char *pathname, char *resolved)
1977 {
1978 const char *rp;
1979
1980 if (pathname == NULL || pathname[0] == '\0')
1981 return NULL;
1982
1983 rp = HashTable_FindValue(&cached_realpaths, pathname);
1984 if (rp != NULL) {
1985 /* a hit */
1986 strncpy(resolved, rp, MAXPATHLEN);
1987 resolved[MAXPATHLEN - 1] = '\0';
1988 return resolved;
1989 }
1990
1991 rp = realpath(pathname, resolved);
1992 if (rp != NULL) {
1993 HashTable_Set(&cached_realpaths, pathname, bmake_strdup(rp));
1994 DEBUG2(DIR, "cached_realpath: %s -> %s\n", pathname, rp);
1995 return resolved;
1996 }
1997
1998 /* should we negative-cache? */
1999 return NULL;
2000 }
2001
2002 /*
2003 * Return true if we should die without noise.
2004 * For example our failing child was a sub-make or failure happened elsewhere.
2005 */
2006 bool
2007 shouldDieQuietly(GNode *gn, int bf)
2008 {
2009 static int quietly = -1;
2010
2011 if (quietly < 0) {
2012 if (DEBUG(JOB) ||
2013 !GetBooleanExpr("${.MAKE.DIE_QUIETLY}", true))
2014 quietly = 0;
2015 else if (bf >= 0)
2016 quietly = bf;
2017 else
2018 quietly = (gn != NULL && (gn->type & OP_MAKE)) ? 1 : 0;
2019 }
2020 return quietly != 0;
2021 }
2022
2023 static void
2024 SetErrorVars(GNode *gn)
2025 {
2026 StringListNode *ln;
2027
2028 /*
2029 * We can print this even if there is no .ERROR target.
2030 */
2031 Global_Set(".ERROR_TARGET", gn->name);
2032 Global_Delete(".ERROR_CMD");
2033
2034 for (ln = gn->commands.first; ln != NULL; ln = ln->next) {
2035 const char *cmd = ln->datum;
2036
2037 if (cmd == NULL)
2038 break;
2039 Global_Append(".ERROR_CMD", cmd);
2040 }
2041 }
2042
2043 /*
2044 * Print some helpful information in case of an error.
2045 * The caller should exit soon after calling this function.
2046 */
2047 void
2048 PrintOnError(GNode *gn, const char *msg)
2049 {
2050 static GNode *errorNode = NULL;
2051
2052 if (DEBUG(HASH)) {
2053 Targ_Stats();
2054 Var_Stats();
2055 }
2056
2057 if (errorNode != NULL)
2058 return; /* we've been here! */
2059
2060 if (msg != NULL)
2061 printf("%s", msg);
2062 printf("\n%s: stopped in %s\n", progname, curdir);
2063
2064 /* we generally want to keep quiet if a sub-make died */
2065 if (shouldDieQuietly(gn, -1))
2066 return;
2067
2068 if (gn != NULL)
2069 SetErrorVars(gn);
2070
2071 {
2072 char *errorVarsValues;
2073 (void)Var_Subst("${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
2074 SCOPE_GLOBAL, VARE_WANTRES, &errorVarsValues);
2075 /* TODO: handle errors */
2076 printf("%s", errorVarsValues);
2077 free(errorVarsValues);
2078 }
2079
2080 fflush(stdout);
2081
2082 /*
2083 * Finally, see if there is a .ERROR target, and run it if so.
2084 */
2085 errorNode = Targ_FindNode(".ERROR");
2086 if (errorNode != NULL) {
2087 errorNode->type |= OP_SPECIAL;
2088 Compat_Make(errorNode, errorNode);
2089 }
2090 }
2091
2092 void
2093 Main_ExportMAKEFLAGS(bool first)
2094 {
2095 static bool once = true;
2096 const char *expr;
2097 char *s;
2098
2099 if (once != first)
2100 return;
2101 once = false;
2102
2103 expr = "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}";
2104 (void)Var_Subst(expr, SCOPE_CMDLINE, VARE_WANTRES, &s);
2105 /* TODO: handle errors */
2106 if (s[0] != '\0') {
2107 #ifdef POSIX
2108 setenv("MAKEFLAGS", s, 1);
2109 #else
2110 setenv("MAKE", s, 1);
2111 #endif
2112 }
2113 }
2114
2115 char *
2116 getTmpdir(void)
2117 {
2118 static char *tmpdir = NULL;
2119 struct stat st;
2120
2121 if (tmpdir != NULL)
2122 return tmpdir;
2123
2124 /* Honor $TMPDIR but only if it is valid. Ensure it ends with '/'. */
2125 (void)Var_Subst("${TMPDIR:tA:U" _PATH_TMP ":S,/$,,W}/",
2126 SCOPE_GLOBAL, VARE_WANTRES, &tmpdir);
2127 /* TODO: handle errors */
2128
2129 if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
2130 free(tmpdir);
2131 tmpdir = bmake_strdup(_PATH_TMP);
2132 }
2133 return tmpdir;
2134 }
2135
2136 /*
2137 * Create and open a temp file using "pattern".
2138 * If out_fname is provided, set it to a copy of the filename created.
2139 * Otherwise unlink the file once open.
2140 */
2141 int
2142 mkTempFile(const char *pattern, char *tfile, size_t tfile_sz)
2143 {
2144 static char *tmpdir = NULL;
2145 char tbuf[MAXPATHLEN];
2146 int fd;
2147
2148 if (pattern == NULL)
2149 pattern = TMPPAT;
2150 if (tmpdir == NULL)
2151 tmpdir = getTmpdir();
2152 if (tfile == NULL) {
2153 tfile = tbuf;
2154 tfile_sz = sizeof tbuf;
2155 }
2156
2157 if (pattern[0] == '/')
2158 snprintf(tfile, tfile_sz, "%s", pattern);
2159 else
2160 snprintf(tfile, tfile_sz, "%s%s", tmpdir, pattern);
2161
2162 if ((fd = mkstemp(tfile)) < 0)
2163 Punt("Could not create temporary file %s: %s", tfile,
2164 strerror(errno));
2165 if (tfile == tbuf)
2166 unlink(tfile); /* we just want the descriptor */
2167
2168 return fd;
2169 }
2170
2171 /*
2172 * Convert a string representation of a boolean into a boolean value.
2173 * Anything that looks like "No", "False", "Off", "0" etc. is false,
2174 * the empty string is the fallback, everything else is true.
2175 */
2176 bool
2177 ParseBoolean(const char *s, bool fallback)
2178 {
2179 char ch = ch_tolower(s[0]);
2180 if (ch == '\0')
2181 return fallback;
2182 if (ch == '0' || ch == 'f' || ch == 'n')
2183 return false;
2184 if (ch == 'o')
2185 return ch_tolower(s[1]) != 'f';
2186 return true;
2187 }
2188