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