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