main.c revision 1.340 1 /* $NetBSD: main.c,v 1.340 2020/09/22 19:51:19 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 * main.c --
73 * The main file for this entire program. Exit routines etc
74 * reside here.
75 *
76 * Utility functions defined in this file:
77 * Main_ParseArgLine Takes a line of arguments, breaks them and
78 * treats them as if they were given when first
79 * invoked. Used by the parse module to implement
80 * the .MFLAGS target.
81 *
82 * Error Print a tagged error message. The global
83 * MAKE variable must have been defined. This
84 * takes a format string and optional arguments
85 * for it.
86 *
87 * Fatal Print an error message and exit. Also takes
88 * a format string and arguments for it.
89 *
90 * Punt Aborts all jobs and exits with a message. Also
91 * takes a format string and arguments for it.
92 *
93 * Finish Finish things up by printing the number of
94 * errors which occurred, as passed to it, and
95 * exiting.
96 */
97
98 #include <sys/types.h>
99 #include <sys/time.h>
100 #include <sys/param.h>
101 #include <sys/resource.h>
102 #include <sys/stat.h>
103 #ifdef MAKE_NATIVE
104 #include <sys/sysctl.h>
105 #endif
106 #include <sys/utsname.h>
107 #include <sys/wait.h>
108
109 #include <ctype.h>
110 #include <errno.h>
111 #include <signal.h>
112 #include <stdarg.h>
113 #include <stdio.h>
114 #include <stdlib.h>
115 #include <time.h>
116
117 #include "make.h"
118 #include "hash.h"
119 #include "dir.h"
120 #include "job.h"
121 #include "pathnames.h"
122 #include "trace.h"
123
124 #ifdef USE_IOVEC
125 #include <sys/uio.h>
126 #endif
127
128 /* "@(#)main.c 8.3 (Berkeley) 3/19/94" */
129 MAKE_RCSID("$NetBSD: main.c,v 1.340 2020/09/22 19:51:19 rillig Exp $");
130 #if defined(MAKE_NATIVE) && !defined(lint)
131 __COPYRIGHT("@(#) Copyright (c) 1988, 1989, 1990, 1993\
132 The Regents of the University of California. All rights reserved.");
133 #endif
134
135 #ifndef DEFMAXLOCAL
136 #define DEFMAXLOCAL DEFMAXJOBS
137 #endif
138
139 StringList * create; /* Targets to be made */
140 time_t now; /* Time at start of make */
141 GNode *DEFAULT; /* .DEFAULT node */
142 Boolean allPrecious; /* .PRECIOUS given on line by itself */
143 Boolean deleteOnError; /* .DELETE_ON_ERROR: set */
144
145 static Boolean noBuiltins; /* -r flag */
146 static StringList * makefiles; /* ordered list of makefiles to read */
147 static int printVars; /* -[vV] argument */
148 #define COMPAT_VARS 1
149 #define EXPAND_VARS 2
150 static StringList * variables; /* list of variables to print
151 * (for -v and -V) */
152 int maxJobs; /* -j argument */
153 static int maxJobTokens; /* -j argument */
154 Boolean compatMake; /* -B argument */
155 int debug; /* -d argument */
156 Boolean debugVflag; /* -dV */
157 Boolean noExecute; /* -n flag */
158 Boolean noRecursiveExecute; /* -N flag */
159 Boolean keepgoing; /* -k flag */
160 Boolean queryFlag; /* -q flag */
161 Boolean touchFlag; /* -t flag */
162 Boolean enterFlag; /* -w flag */
163 Boolean enterFlagObj; /* -w and objdir != srcdir */
164 Boolean ignoreErrors; /* -i flag */
165 Boolean beSilent; /* -s flag */
166 Boolean oldVars; /* variable substitution style */
167 Boolean checkEnvFirst; /* -e flag */
168 Boolean parseWarnFatal; /* -W flag */
169 static int jp_0 = -1, jp_1 = -1; /* ends of parent job pipe */
170 Boolean varNoExportEnv; /* -X flag */
171 Boolean doing_depend; /* Set while reading .depend */
172 static Boolean jobsRunning; /* TRUE if the jobs might be running */
173 static const char * tracefile;
174 static void MainParseArgs(int, char **);
175 static int ReadMakefile(const char *);
176 static void usage(void) MAKE_ATTR_DEAD;
177 static void purge_cached_realpaths(void);
178
179 static Boolean ignorePWD; /* if we use -C, PWD is meaningless */
180 static char objdir[MAXPATHLEN + 1]; /* where we chdir'ed to */
181 char curdir[MAXPATHLEN + 1]; /* Startup directory */
182 char *progname; /* the program name */
183 char *makeDependfile;
184 pid_t myPid;
185 int makelevel;
186
187 FILE *debug_file;
188
189 Boolean forceJobs = FALSE;
190
191 extern SearchPath *parseIncPath;
192
193 /*
194 * For compatibility with the POSIX version of MAKEFLAGS that includes
195 * all the options with out -, convert flags to -f -l -a -g -s.
196 */
197 static char *
198 explode(const char *flags)
199 {
200 size_t len;
201 char *nf, *st;
202 const char *f;
203
204 if (flags == NULL)
205 return NULL;
206
207 for (f = flags; *f; f++)
208 if (!ch_isalpha(*f))
209 break;
210
211 if (*f)
212 return bmake_strdup(flags);
213
214 len = strlen(flags);
215 st = nf = bmake_malloc(len * 3 + 1);
216 while (*flags) {
217 *nf++ = '-';
218 *nf++ = *flags++;
219 *nf++ = ' ';
220 }
221 *nf = '\0';
222 return st;
223 }
224
225 static void
226 parse_debug_options(const char *argvalue)
227 {
228 const char *modules;
229 const char *mode;
230 char *fname;
231 int len;
232
233 for (modules = argvalue; *modules; ++modules) {
234 switch (*modules) {
235 case 'A':
236 debug = ~(0|DEBUG_LINT);
237 break;
238 case 'a':
239 debug |= DEBUG_ARCH;
240 break;
241 case 'C':
242 debug |= DEBUG_CWD;
243 break;
244 case 'c':
245 debug |= DEBUG_COND;
246 break;
247 case 'd':
248 debug |= DEBUG_DIR;
249 break;
250 case 'e':
251 debug |= DEBUG_ERROR;
252 break;
253 case 'f':
254 debug |= DEBUG_FOR;
255 break;
256 case 'g':
257 if (modules[1] == '1') {
258 debug |= DEBUG_GRAPH1;
259 ++modules;
260 }
261 else if (modules[1] == '2') {
262 debug |= DEBUG_GRAPH2;
263 ++modules;
264 }
265 else if (modules[1] == '3') {
266 debug |= DEBUG_GRAPH3;
267 ++modules;
268 }
269 break;
270 case 'h':
271 debug |= DEBUG_HASH;
272 break;
273 case 'j':
274 debug |= DEBUG_JOB;
275 break;
276 case 'L':
277 debug |= DEBUG_LINT;
278 break;
279 case 'l':
280 debug |= DEBUG_LOUD;
281 break;
282 case 'M':
283 debug |= DEBUG_META;
284 break;
285 case 'm':
286 debug |= DEBUG_MAKE;
287 break;
288 case 'n':
289 debug |= DEBUG_SCRIPT;
290 break;
291 case 'p':
292 debug |= DEBUG_PARSE;
293 break;
294 case 's':
295 debug |= DEBUG_SUFF;
296 break;
297 case 't':
298 debug |= DEBUG_TARG;
299 break;
300 case 'V':
301 debugVflag = TRUE;
302 break;
303 case 'v':
304 debug |= DEBUG_VAR;
305 break;
306 case 'x':
307 debug |= DEBUG_SHELL;
308 break;
309 case 'F':
310 if (debug_file != stdout && debug_file != stderr)
311 fclose(debug_file);
312 if (*++modules == '+') {
313 modules++;
314 mode = "a";
315 } else
316 mode = "w";
317 if (strcmp(modules, "stdout") == 0) {
318 debug_file = stdout;
319 goto debug_setbuf;
320 }
321 if (strcmp(modules, "stderr") == 0) {
322 debug_file = stderr;
323 goto debug_setbuf;
324 }
325 len = strlen(modules);
326 fname = bmake_malloc(len + 20);
327 memcpy(fname, modules, len + 1);
328 /* Let the filename be modified by the pid */
329 if (strcmp(fname + len - 3, ".%d") == 0)
330 snprintf(fname + len - 2, 20, "%d", getpid());
331 debug_file = fopen(fname, mode);
332 if (!debug_file) {
333 fprintf(stderr, "Cannot open debug file %s\n",
334 fname);
335 usage();
336 }
337 free(fname);
338 goto debug_setbuf;
339 default:
340 (void)fprintf(stderr,
341 "%s: illegal argument to d option -- %c\n",
342 progname, *modules);
343 usage();
344 }
345 }
346 debug_setbuf:
347 /*
348 * Make the debug_file unbuffered, and make
349 * stdout line buffered (unless debugfile == stdout).
350 */
351 setvbuf(debug_file, NULL, _IONBF, 0);
352 if (debug_file != stdout) {
353 setvbuf(stdout, NULL, _IOLBF, 0);
354 }
355 }
356
357 /*
358 * does path contain any relative components
359 */
360 static Boolean
361 is_relpath(const char *path)
362 {
363 const char *cp;
364
365 if (path[0] != '/')
366 return TRUE;
367 cp = path;
368 while ((cp = strstr(cp, "/.")) != NULL) {
369 cp += 2;
370 if (cp[0] == '/' || cp[0] == '\0')
371 return TRUE;
372 else if (cp[0] == '.') {
373 if (cp[1] == '/' || cp[1] == '\0')
374 return TRUE;
375 }
376 }
377 return FALSE;
378 }
379
380 /*-
381 * MainParseArgs --
382 * Parse a given argument vector. Called from main() and from
383 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
384 *
385 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
386 *
387 * Results:
388 * None
389 *
390 * Side Effects:
391 * Various global and local flags will be set depending on the flags
392 * given
393 */
394 static void
395 MainParseArgs(int argc, char **argv)
396 {
397 char *p;
398 char c = '?';
399 int arginc;
400 char *argvalue;
401 const char *getopt_def;
402 struct stat sa, sb;
403 char *optscan;
404 Boolean inOption, dashDash = FALSE;
405 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
406
407 #define OPTFLAGS "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrstv:w"
408 /* Can't actually use getopt(3) because rescanning is not portable */
409
410 getopt_def = OPTFLAGS;
411 rearg:
412 inOption = FALSE;
413 optscan = NULL;
414 while(argc > 1) {
415 char *getopt_spec;
416 if(!inOption)
417 optscan = argv[1];
418 c = *optscan++;
419 arginc = 0;
420 if(inOption) {
421 if(c == '\0') {
422 ++argv;
423 --argc;
424 inOption = FALSE;
425 continue;
426 }
427 } else {
428 if (c != '-' || dashDash)
429 break;
430 inOption = TRUE;
431 c = *optscan++;
432 }
433 /* '-' found at some earlier point */
434 getopt_spec = strchr(getopt_def, c);
435 if(c != '\0' && getopt_spec != NULL && getopt_spec[1] == ':') {
436 /* -<something> found, and <something> should have an arg */
437 inOption = FALSE;
438 arginc = 1;
439 argvalue = optscan;
440 if(*argvalue == '\0') {
441 if (argc < 3)
442 goto noarg;
443 argvalue = argv[2];
444 arginc = 2;
445 }
446 } else {
447 argvalue = NULL;
448 }
449 switch(c) {
450 case '\0':
451 arginc = 1;
452 inOption = FALSE;
453 break;
454 case 'B':
455 compatMake = TRUE;
456 Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
457 Var_Set(MAKE_MODE, "compat", VAR_GLOBAL);
458 break;
459 case 'C':
460 if (chdir(argvalue) == -1) {
461 (void)fprintf(stderr,
462 "%s: chdir %s: %s\n",
463 progname, argvalue,
464 strerror(errno));
465 exit(1);
466 }
467 if (getcwd(curdir, MAXPATHLEN) == NULL) {
468 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
469 exit(2);
470 }
471 if (!is_relpath(argvalue) &&
472 stat(argvalue, &sa) != -1 &&
473 stat(curdir, &sb) != -1 &&
474 sa.st_ino == sb.st_ino &&
475 sa.st_dev == sb.st_dev)
476 strncpy(curdir, argvalue, MAXPATHLEN);
477 ignorePWD = TRUE;
478 break;
479 case 'D':
480 if (argvalue == NULL || argvalue[0] == 0) goto noarg;
481 Var_Set(argvalue, "1", VAR_GLOBAL);
482 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
483 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
484 break;
485 case 'I':
486 if (argvalue == NULL) goto noarg;
487 Parse_AddIncludeDir(argvalue);
488 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
489 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
490 break;
491 case 'J':
492 if (argvalue == NULL) goto noarg;
493 if (sscanf(argvalue, "%d,%d", &jp_0, &jp_1) != 2) {
494 (void)fprintf(stderr,
495 "%s: internal error -- J option malformed (%s)\n",
496 progname, argvalue);
497 usage();
498 }
499 if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
500 (fcntl(jp_1, F_GETFD, 0) < 0)) {
501 #if 0
502 (void)fprintf(stderr,
503 "%s: ###### warning -- J descriptors were closed!\n",
504 progname);
505 exit(2);
506 #endif
507 jp_0 = -1;
508 jp_1 = -1;
509 compatMake = TRUE;
510 } else {
511 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
512 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
513 }
514 break;
515 case 'N':
516 noExecute = TRUE;
517 noRecursiveExecute = TRUE;
518 Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
519 break;
520 case 'S':
521 keepgoing = FALSE;
522 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
523 break;
524 case 'T':
525 if (argvalue == NULL) goto noarg;
526 tracefile = bmake_strdup(argvalue);
527 Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
528 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
529 break;
530 case 'V':
531 case 'v':
532 if (argvalue == NULL) goto noarg;
533 printVars = c == 'v' ? EXPAND_VARS : COMPAT_VARS;
534 Lst_Append(variables, argvalue);
535 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
536 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
537 break;
538 case 'W':
539 parseWarnFatal = TRUE;
540 break;
541 case 'X':
542 varNoExportEnv = TRUE;
543 Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
544 break;
545 case 'd':
546 if (argvalue == NULL) goto noarg;
547 /* If '-d-opts' don't pass to children */
548 if (argvalue[0] == '-')
549 argvalue++;
550 else {
551 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
552 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
553 }
554 parse_debug_options(argvalue);
555 break;
556 case 'e':
557 checkEnvFirst = TRUE;
558 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
559 break;
560 case 'f':
561 if (argvalue == NULL) goto noarg;
562 Lst_Append(makefiles, argvalue);
563 break;
564 case 'i':
565 ignoreErrors = TRUE;
566 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
567 break;
568 case 'j':
569 if (argvalue == NULL) goto noarg;
570 forceJobs = TRUE;
571 maxJobs = strtol(argvalue, &p, 0);
572 if (*p != '\0' || maxJobs < 1) {
573 (void)fprintf(stderr, "%s: illegal argument to -j -- must be positive integer!\n",
574 progname);
575 exit(1);
576 }
577 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
578 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
579 Var_Set(".MAKE.JOBS", argvalue, VAR_GLOBAL);
580 maxJobTokens = maxJobs;
581 break;
582 case 'k':
583 keepgoing = TRUE;
584 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
585 break;
586 case 'm':
587 if (argvalue == NULL) goto noarg;
588 /* look for magic parent directory search string */
589 if (strncmp(".../", argvalue, 4) == 0) {
590 if (!Dir_FindHereOrAbove(curdir, argvalue+4,
591 found_path, sizeof(found_path)))
592 break; /* nothing doing */
593 (void)Dir_AddDir(sysIncPath, found_path);
594 } else {
595 (void)Dir_AddDir(sysIncPath, argvalue);
596 }
597 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
598 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
599 break;
600 case 'n':
601 noExecute = TRUE;
602 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
603 break;
604 case 'q':
605 queryFlag = TRUE;
606 /* Kind of nonsensical, wot? */
607 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
608 break;
609 case 'r':
610 noBuiltins = TRUE;
611 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
612 break;
613 case 's':
614 beSilent = TRUE;
615 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
616 break;
617 case 't':
618 touchFlag = TRUE;
619 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
620 break;
621 case 'w':
622 enterFlag = TRUE;
623 Var_Append(MAKEFLAGS, "-w", VAR_GLOBAL);
624 break;
625 case '-':
626 dashDash = TRUE;
627 break;
628 default:
629 case '?':
630 usage();
631 }
632 argv += arginc;
633 argc -= arginc;
634 }
635
636 oldVars = TRUE;
637
638 /*
639 * See if the rest of the arguments are variable assignments and
640 * perform them if so. Else take them to be targets and stuff them
641 * on the end of the "create" list.
642 */
643 for (; argc > 1; ++argv, --argc)
644 if (Parse_IsVar(argv[1])) {
645 Parse_DoVar(argv[1], VAR_CMD);
646 } else {
647 if (!*argv[1])
648 Punt("illegal (null) argument.");
649 if (*argv[1] == '-' && !dashDash)
650 goto rearg;
651 Lst_Append(create, bmake_strdup(argv[1]));
652 }
653
654 return;
655 noarg:
656 (void)fprintf(stderr, "%s: option requires an argument -- %c\n",
657 progname, c);
658 usage();
659 }
660
661 /*-
662 * Main_ParseArgLine --
663 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
664 * is encountered and by main() when reading the .MAKEFLAGS envariable.
665 * Takes a line of arguments and breaks it into its
666 * component words and passes those words and the number of them to the
667 * MainParseArgs function.
668 * The line should have all its leading whitespace removed.
669 *
670 * Input:
671 * line Line to fracture
672 *
673 * Results:
674 * None
675 *
676 * Side Effects:
677 * Only those that come from the various arguments.
678 */
679 void
680 Main_ParseArgLine(const char *line)
681 {
682 Words words;
683 char *p1;
684 const char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
685 char *buf;
686
687 if (line == NULL)
688 return;
689 for (; *line == ' '; ++line)
690 continue;
691 if (!*line)
692 return;
693
694 buf = str_concat3(argv0, " ", line);
695 free(p1);
696
697 words = Str_Words(buf, TRUE);
698 if (words.words == NULL) {
699 Error("Unterminated quoted string [%s]", buf);
700 free(buf);
701 return;
702 }
703 free(buf);
704 MainParseArgs((int)words.len, words.words);
705
706 Words_Free(words);
707 }
708
709 Boolean
710 Main_SetObjdir(const char *fmt, ...)
711 {
712 struct stat sb;
713 char *path;
714 char buf[MAXPATHLEN + 1];
715 char buf2[MAXPATHLEN + 1];
716 Boolean rc = FALSE;
717 va_list ap;
718
719 va_start(ap, fmt);
720 vsnprintf(path = buf, MAXPATHLEN, fmt, ap);
721 va_end(ap);
722
723 if (path[0] != '/') {
724 snprintf(buf2, MAXPATHLEN, "%s/%s", curdir, path);
725 path = buf2;
726 }
727
728 /* look for the directory and try to chdir there */
729 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
730 if (chdir(path)) {
731 (void)fprintf(stderr, "make warning: %s: %s.\n",
732 path, strerror(errno));
733 } else {
734 snprintf(objdir, sizeof objdir, "%s", path);
735 Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
736 setenv("PWD", objdir, 1);
737 Dir_InitDot();
738 purge_cached_realpaths();
739 rc = TRUE;
740 if (enterFlag && strcmp(objdir, curdir) != 0)
741 enterFlagObj = TRUE;
742 }
743 }
744
745 return rc;
746 }
747
748 static Boolean
749 Main_SetVarObjdir(const char *var, const char *suffix)
750 {
751 char *path_freeIt;
752 const char *path = Var_Value(var, VAR_CMD, &path_freeIt);
753 const char *xpath;
754 char *xpath_freeIt;
755
756 if (path == NULL || path[0] == '\0') {
757 bmake_free(path_freeIt);
758 return FALSE;
759 }
760
761 /* expand variable substitutions */
762 xpath = path;
763 xpath_freeIt = NULL;
764 if (strchr(path, '$') != 0)
765 xpath = xpath_freeIt = Var_Subst(path, VAR_GLOBAL,
766 VARE_WANTRES);
767
768 (void)Main_SetObjdir("%s%s", xpath, suffix);
769
770 bmake_free(xpath_freeIt);
771 bmake_free(path_freeIt);
772 return TRUE;
773 }
774
775 /* Read and parse the makefile.
776 * Return TRUE if reading the makefile succeeded, for Lst_Find. */
777 static Boolean
778 ReadMakefileSucceeded(const void *fname, const void *unused)
779 {
780 return ReadMakefile(fname) == 0;
781 }
782
783 /* Read and parse the makefile.
784 * Return TRUE if reading the makefile failed, for Lst_Find. */
785 static Boolean
786 ReadMakefileFailed(const void *fname, const void *unused)
787 {
788 return ReadMakefile(fname) != 0;
789 }
790
791 int
792 str2Lst_Append(StringList *lp, char *str, const char *sep)
793 {
794 char *cp;
795 int n;
796
797 if (!sep)
798 sep = " \t";
799
800 for (n = 0, cp = strtok(str, sep); cp; cp = strtok(NULL, sep)) {
801 Lst_Append(lp, cp);
802 n++;
803 }
804 return n;
805 }
806
807 #ifdef SIGINFO
808 /*ARGSUSED*/
809 static void
810 siginfo(int signo MAKE_ATTR_UNUSED)
811 {
812 char dir[MAXPATHLEN];
813 char str[2 * MAXPATHLEN];
814 int len;
815 if (getcwd(dir, sizeof(dir)) == NULL)
816 return;
817 len = snprintf(str, sizeof(str), "%s: Working in: %s\n", progname, dir);
818 if (len > 0)
819 (void)write(STDERR_FILENO, str, (size_t)len);
820 }
821 #endif
822
823 /*
824 * Allow makefiles some control over the mode we run in.
825 */
826 void
827 MakeMode(const char *mode)
828 {
829 char *mode_freeIt = NULL;
830
831 if (mode == NULL)
832 mode = mode_freeIt = Var_Subst("${" MAKE_MODE ":tl}",
833 VAR_GLOBAL, VARE_WANTRES);
834
835 if (mode[0] != '\0') {
836 if (strstr(mode, "compat")) {
837 compatMake = TRUE;
838 forceJobs = FALSE;
839 }
840 #if USE_META
841 if (strstr(mode, "meta"))
842 meta_mode_init(mode);
843 #endif
844 }
845
846 free(mode_freeIt);
847 }
848
849 static void
850 doPrintVars(void)
851 {
852 StringListNode *ln;
853 Boolean expandVars;
854
855 if (printVars == EXPAND_VARS)
856 expandVars = TRUE;
857 else if (debugVflag)
858 expandVars = FALSE;
859 else
860 expandVars = getBoolean(".MAKE.EXPAND_VARIABLES", FALSE);
861
862 for (ln = Lst_First(variables); ln != NULL; ln = LstNode_Next(ln)) {
863 char *var = LstNode_Datum(ln);
864 const char *value;
865 char *p1;
866
867 if (strchr(var, '$')) {
868 value = p1 = Var_Subst(var, VAR_GLOBAL, VARE_WANTRES);
869 } else if (expandVars) {
870 char *expr = str_concat3("${", var, "}");
871 value = p1 = Var_Subst(expr, VAR_GLOBAL, VARE_WANTRES);
872 free(expr);
873 } else {
874 value = Var_Value(var, VAR_GLOBAL, &p1);
875 }
876 printf("%s\n", value ? value : "");
877 bmake_free(p1);
878 }
879 }
880
881 static Boolean
882 runTargets(void)
883 {
884 GNodeList *targs; /* target nodes to create -- passed to Make_Init */
885 Boolean outOfDate; /* FALSE if all targets up to date */
886
887 /*
888 * Have now read the entire graph and need to make a list of
889 * targets to create. If none was given on the command line,
890 * we consult the parsing module to find the main target(s)
891 * to create.
892 */
893 if (Lst_IsEmpty(create))
894 targs = Parse_MainName();
895 else
896 targs = Targ_FindList(create, TARG_CREATE);
897
898 if (!compatMake) {
899 /*
900 * Initialize job module before traversing the graph
901 * now that any .BEGIN and .END targets have been read.
902 * This is done only if the -q flag wasn't given
903 * (to prevent the .BEGIN from being executed should
904 * it exist).
905 */
906 if (!queryFlag) {
907 Job_Init();
908 jobsRunning = TRUE;
909 }
910
911 /* Traverse the graph, checking on all the targets */
912 outOfDate = Make_Run(targs);
913 } else {
914 /*
915 * Compat_Init will take care of creating all the
916 * targets as well as initializing the module.
917 */
918 Compat_Run(targs);
919 outOfDate = FALSE;
920 }
921 Lst_Free(targs);
922 return outOfDate;
923 }
924
925 /*-
926 * main --
927 * The main function, for obvious reasons. Initializes variables
928 * and a few modules, then parses the arguments give it in the
929 * environment and on the command line. Reads the system makefile
930 * followed by either Makefile, makefile or the file given by the
931 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
932 * flags it has received by then uses either the Make or the Compat
933 * module to create the initial list of targets.
934 *
935 * Results:
936 * If -q was given, exits -1 if anything was out-of-date. Else it exits
937 * 0.
938 *
939 * Side Effects:
940 * The program exits when done. Targets are created. etc. etc. etc.
941 */
942 int
943 main(int argc, char **argv)
944 {
945 Boolean outOfDate; /* FALSE if all targets up to date */
946 struct stat sb, sa;
947 char *p1, *path;
948 char mdpath[MAXPATHLEN];
949 const char *machine = getenv("MACHINE");
950 const char *machine_arch = getenv("MACHINE_ARCH");
951 char *syspath = getenv("MAKESYSPATH");
952 StringList *sysMkPath; /* Path of sys.mk */
953 char *cp = NULL, *start;
954 /* avoid faults on read-only strings */
955 static char defsyspath[] = _PATH_DEFSYSPATH;
956 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
957 struct timeval rightnow; /* to initialize random seed */
958 struct utsname utsname;
959
960 /* default to writing debug to stderr */
961 debug_file = stderr;
962
963 #ifdef SIGINFO
964 (void)bmake_signal(SIGINFO, siginfo);
965 #endif
966 /*
967 * Set the seed to produce a different random sequence
968 * on each program execution.
969 */
970 gettimeofday(&rightnow, NULL);
971 srandom(rightnow.tv_sec + rightnow.tv_usec);
972
973 if ((progname = strrchr(argv[0], '/')) != NULL)
974 progname++;
975 else
976 progname = argv[0];
977 #if defined(MAKE_NATIVE) || (defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE))
978 /*
979 * get rid of resource limit on file descriptors
980 */
981 {
982 struct rlimit rl;
983 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
984 rl.rlim_cur != rl.rlim_max) {
985 rl.rlim_cur = rl.rlim_max;
986 (void)setrlimit(RLIMIT_NOFILE, &rl);
987 }
988 }
989 #endif
990
991 if (uname(&utsname) == -1) {
992 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
993 strerror(errno));
994 exit(2);
995 }
996
997 /*
998 * Get the name of this type of MACHINE from utsname
999 * so we can share an executable for similar machines.
1000 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
1001 *
1002 * Note that both MACHINE and MACHINE_ARCH are decided at
1003 * run-time.
1004 */
1005 if (!machine) {
1006 #ifdef MAKE_NATIVE
1007 machine = utsname.machine;
1008 #else
1009 #ifdef MAKE_MACHINE
1010 machine = MAKE_MACHINE;
1011 #else
1012 machine = "unknown";
1013 #endif
1014 #endif
1015 }
1016
1017 if (!machine_arch) {
1018 #ifdef MAKE_NATIVE
1019 static char machine_arch_buf[sizeof(utsname.machine)];
1020 const int mib[2] = { CTL_HW, HW_MACHINE_ARCH };
1021 size_t len = sizeof(machine_arch_buf);
1022
1023 if (sysctl(mib, __arraycount(mib), machine_arch_buf,
1024 &len, NULL, 0) < 0) {
1025 (void)fprintf(stderr, "%s: sysctl failed (%s).\n", progname,
1026 strerror(errno));
1027 exit(2);
1028 }
1029
1030 machine_arch = machine_arch_buf;
1031 #else
1032 #ifndef MACHINE_ARCH
1033 #ifdef MAKE_MACHINE_ARCH
1034 machine_arch = MAKE_MACHINE_ARCH;
1035 #else
1036 machine_arch = "unknown";
1037 #endif
1038 #else
1039 machine_arch = MACHINE_ARCH;
1040 #endif
1041 #endif
1042 }
1043
1044 myPid = getpid(); /* remember this for vFork() */
1045
1046 /*
1047 * Just in case MAKEOBJDIR wants us to do something tricky.
1048 */
1049 Var_Init(); /* Initialize the lists of variables for
1050 * parsing arguments */
1051 Var_Set(".MAKE.OS", utsname.sysname, VAR_GLOBAL);
1052 Var_Set("MACHINE", machine, VAR_GLOBAL);
1053 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
1054 #ifdef MAKE_VERSION
1055 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
1056 #endif
1057 Var_Set(".newline", "\n", VAR_GLOBAL); /* handy for :@ loops */
1058 /*
1059 * This is the traditional preference for makefiles.
1060 */
1061 #ifndef MAKEFILE_PREFERENCE_LIST
1062 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
1063 #endif
1064 Var_Set(MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST,
1065 VAR_GLOBAL);
1066 Var_Set(MAKE_DEPENDFILE, ".depend", VAR_GLOBAL);
1067
1068 create = Lst_Init();
1069 makefiles = Lst_Init();
1070 printVars = 0;
1071 debugVflag = FALSE;
1072 variables = Lst_Init();
1073 beSilent = FALSE; /* Print commands as executed */
1074 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
1075 noExecute = FALSE; /* Execute all commands */
1076 noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
1077 keepgoing = FALSE; /* Stop on error */
1078 allPrecious = FALSE; /* Remove targets when interrupted */
1079 deleteOnError = FALSE; /* Historical default behavior */
1080 queryFlag = FALSE; /* This is not just a check-run */
1081 noBuiltins = FALSE; /* Read the built-in rules */
1082 touchFlag = FALSE; /* Actually update targets */
1083 debug = 0; /* No debug verbosity, please. */
1084 jobsRunning = FALSE;
1085
1086 maxJobs = DEFMAXLOCAL; /* Set default local max concurrency */
1087 maxJobTokens = maxJobs;
1088 compatMake = FALSE; /* No compat mode */
1089 ignorePWD = FALSE;
1090
1091 /*
1092 * Initialize the parsing, directory and variable modules to prepare
1093 * for the reading of inclusion paths and variable settings on the
1094 * command line
1095 */
1096
1097 /*
1098 * Initialize various variables.
1099 * MAKE also gets this name, for compatibility
1100 * .MAKEFLAGS gets set to the empty string just in case.
1101 * MFLAGS also gets initialized empty, for compatibility.
1102 */
1103 Parse_Init();
1104 if (argv[0][0] == '/' || strchr(argv[0], '/') == NULL) {
1105 /*
1106 * Leave alone if it is an absolute path, or if it does
1107 * not contain a '/' in which case we need to find it in
1108 * the path, like execvp(3) and the shells do.
1109 */
1110 p1 = argv[0];
1111 } else {
1112 /*
1113 * A relative path, canonicalize it.
1114 */
1115 p1 = cached_realpath(argv[0], mdpath);
1116 if (!p1 || *p1 != '/' || stat(p1, &sb) < 0) {
1117 p1 = argv[0]; /* realpath failed */
1118 }
1119 }
1120 Var_Set("MAKE", p1, VAR_GLOBAL);
1121 Var_Set(".MAKE", p1, VAR_GLOBAL);
1122 Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
1123 Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL);
1124 Var_Set("MFLAGS", "", VAR_GLOBAL);
1125 Var_Set(".ALLTARGETS", "", VAR_GLOBAL);
1126 /* some makefiles need to know this */
1127 Var_Set(MAKE_LEVEL ".ENV", MAKE_LEVEL_ENV, VAR_CMD);
1128
1129 /*
1130 * Set some other useful macros
1131 */
1132 {
1133 char tmp[64], *ep;
1134
1135 makelevel = ((ep = getenv(MAKE_LEVEL_ENV)) && *ep) ? atoi(ep) : 0;
1136 if (makelevel < 0)
1137 makelevel = 0;
1138 snprintf(tmp, sizeof(tmp), "%d", makelevel);
1139 Var_Set(MAKE_LEVEL, tmp, VAR_GLOBAL);
1140 snprintf(tmp, sizeof(tmp), "%u", myPid);
1141 Var_Set(".MAKE.PID", tmp, VAR_GLOBAL);
1142 snprintf(tmp, sizeof(tmp), "%u", getppid());
1143 Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL);
1144 }
1145 if (makelevel > 0) {
1146 char pn[1024];
1147 snprintf(pn, sizeof(pn), "%s[%d]", progname, makelevel);
1148 progname = bmake_strdup(pn);
1149 }
1150
1151 #ifdef USE_META
1152 meta_init();
1153 #endif
1154 Dir_Init();
1155
1156 /*
1157 * First snag any flags out of the MAKE environment variable.
1158 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
1159 * in a different format).
1160 */
1161 #ifdef POSIX
1162 p1 = explode(getenv("MAKEFLAGS"));
1163 Main_ParseArgLine(p1);
1164 free(p1);
1165 #else
1166 Main_ParseArgLine(getenv("MAKE"));
1167 #endif
1168
1169 /*
1170 * Find where we are (now).
1171 * We take care of PWD for the automounter below...
1172 */
1173 if (getcwd(curdir, MAXPATHLEN) == NULL) {
1174 (void)fprintf(stderr, "%s: getcwd: %s.\n",
1175 progname, strerror(errno));
1176 exit(2);
1177 }
1178
1179 MainParseArgs(argc, argv);
1180
1181 if (enterFlag)
1182 printf("%s: Entering directory `%s'\n", progname, curdir);
1183
1184 /*
1185 * Verify that cwd is sane.
1186 */
1187 if (stat(curdir, &sa) == -1) {
1188 (void)fprintf(stderr, "%s: %s: %s.\n",
1189 progname, curdir, strerror(errno));
1190 exit(2);
1191 }
1192
1193 /*
1194 * All this code is so that we know where we are when we start up
1195 * on a different machine with pmake.
1196 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
1197 * since the value of curdir can vary depending on how we got
1198 * here. Ie sitting at a shell prompt (shell that provides $PWD)
1199 * or via subdir.mk in which case its likely a shell which does
1200 * not provide it.
1201 * So, to stop it breaking this case only, we ignore PWD if
1202 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
1203 */
1204 #ifndef NO_PWD_OVERRIDE
1205 if (!ignorePWD) {
1206 char *pwd, *ptmp1 = NULL, *ptmp2 = NULL;
1207
1208 if ((pwd = getenv("PWD")) != NULL &&
1209 Var_Value("MAKEOBJDIRPREFIX", VAR_CMD, &ptmp1) == NULL) {
1210 const char *makeobjdir = Var_Value("MAKEOBJDIR",
1211 VAR_CMD, &ptmp2);
1212
1213 if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
1214 if (stat(pwd, &sb) == 0 &&
1215 sa.st_ino == sb.st_ino &&
1216 sa.st_dev == sb.st_dev)
1217 (void)strncpy(curdir, pwd, MAXPATHLEN);
1218 }
1219 }
1220 bmake_free(ptmp1);
1221 bmake_free(ptmp2);
1222 }
1223 #endif
1224 Var_Set(".CURDIR", curdir, VAR_GLOBAL);
1225
1226 /*
1227 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
1228 * MAKEOBJDIR is set in the environment, try only that value
1229 * and fall back to .CURDIR if it does not exist.
1230 *
1231 * Otherwise, try _PATH_OBJDIR.MACHINE-MACHINE_ARCH, _PATH_OBJDIR.MACHINE,
1232 * and * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
1233 * of these paths exist, just use .CURDIR.
1234 */
1235 Dir_InitDir(curdir);
1236 (void)Main_SetObjdir("%s", curdir);
1237
1238 if (!Main_SetVarObjdir("MAKEOBJDIRPREFIX", curdir) &&
1239 !Main_SetVarObjdir("MAKEOBJDIR", "") &&
1240 !Main_SetObjdir("%s.%s-%s", _PATH_OBJDIR, machine, machine_arch) &&
1241 !Main_SetObjdir("%s.%s", _PATH_OBJDIR, machine) &&
1242 !Main_SetObjdir("%s", _PATH_OBJDIR))
1243 (void)Main_SetObjdir("%s%s", _PATH_OBJDIRPREFIX, curdir);
1244
1245 /*
1246 * Initialize archive, target and suffix modules in preparation for
1247 * parsing the makefile(s)
1248 */
1249 Arch_Init();
1250 Targ_Init();
1251 Suff_Init();
1252 Trace_Init(tracefile);
1253
1254 DEFAULT = NULL;
1255 (void)time(&now);
1256
1257 Trace_Log(MAKESTART, NULL);
1258
1259 /*
1260 * Set up the .TARGETS variable to contain the list of targets to be
1261 * created. If none specified, make the variable empty -- the parser
1262 * will fill the thing in with the default or .MAIN target.
1263 */
1264 if (!Lst_IsEmpty(create)) {
1265 StringListNode *ln;
1266
1267 for (ln = Lst_First(create); ln != NULL; ln = LstNode_Next(ln)) {
1268 char *name = LstNode_Datum(ln);
1269 Var_Append(".TARGETS", name, VAR_GLOBAL);
1270 }
1271 } else
1272 Var_Set(".TARGETS", "", VAR_GLOBAL);
1273
1274
1275 /*
1276 * If no user-supplied system path was given (through the -m option)
1277 * add the directories from the DEFSYSPATH (more than one may be given
1278 * as dir1:...:dirn) to the system include path.
1279 */
1280 /* XXX: mismatch: the -m option sets sysIncPath, not syspath */
1281 if (syspath == NULL || syspath[0] == '\0')
1282 syspath = defsyspath;
1283 else
1284 syspath = bmake_strdup(syspath);
1285
1286 for (start = syspath; *start != '\0'; start = cp) {
1287 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1288 continue;
1289 if (*cp == ':') {
1290 *cp++ = '\0';
1291 }
1292 /* look for magic parent directory search string */
1293 if (strncmp(".../", start, 4) != 0) {
1294 (void)Dir_AddDir(defIncPath, start);
1295 } else {
1296 if (Dir_FindHereOrAbove(curdir, start+4,
1297 found_path, sizeof(found_path))) {
1298 (void)Dir_AddDir(defIncPath, found_path);
1299 }
1300 }
1301 }
1302 if (syspath != defsyspath)
1303 free(syspath);
1304
1305 /*
1306 * Read in the built-in rules first, followed by the specified
1307 * makefiles, or the default makefile and Makefile, in that order,
1308 * if no makefiles were given on the command line.
1309 */
1310 if (!noBuiltins) {
1311 StringListNode *ln;
1312
1313 sysMkPath = Lst_Init();
1314 Dir_Expand(_PATH_DEFSYSMK,
1315 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
1316 sysMkPath);
1317 if (Lst_IsEmpty(sysMkPath))
1318 Fatal("%s: no system rules (%s).", progname,
1319 _PATH_DEFSYSMK);
1320 ln = Lst_Find(sysMkPath, ReadMakefileSucceeded, NULL);
1321 if (ln == NULL)
1322 Fatal("%s: cannot open %s.", progname,
1323 (char *)LstNode_Datum(Lst_First(sysMkPath)));
1324 }
1325
1326 if (!Lst_IsEmpty(makefiles)) {
1327 StringListNode *ln;
1328
1329 ln = Lst_Find(makefiles, ReadMakefileFailed, NULL);
1330 if (ln != NULL)
1331 Fatal("%s: cannot open %s.", progname,
1332 (char *)LstNode_Datum(ln));
1333 } else {
1334 p1 = Var_Subst("${" MAKEFILE_PREFERENCE "}",
1335 VAR_CMD, VARE_WANTRES);
1336 (void)str2Lst_Append(makefiles, p1, NULL);
1337 (void)Lst_Find(makefiles, ReadMakefileSucceeded, NULL);
1338 free(p1);
1339 }
1340
1341 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1342 if (!noBuiltins || !printVars) {
1343 makeDependfile = Var_Subst("${.MAKE.DEPENDFILE:T}",
1344 VAR_CMD, VARE_WANTRES);
1345 doing_depend = TRUE;
1346 (void)ReadMakefile(makeDependfile);
1347 doing_depend = FALSE;
1348 }
1349
1350 if (enterFlagObj)
1351 printf("%s: Entering directory `%s'\n", progname, objdir);
1352
1353 MakeMode(NULL);
1354
1355 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
1356 bmake_free(p1);
1357
1358 if (!forceJobs && !compatMake &&
1359 Var_Exists(".MAKE.JOBS", VAR_GLOBAL)) {
1360 char *value;
1361 int n;
1362
1363 value = Var_Subst("${.MAKE.JOBS}", VAR_GLOBAL, VARE_WANTRES);
1364 n = strtol(value, NULL, 0);
1365 if (n < 1) {
1366 (void)fprintf(stderr, "%s: illegal value for .MAKE.JOBS -- must be positive integer!\n",
1367 progname);
1368 exit(1);
1369 }
1370 if (n != maxJobs) {
1371 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
1372 Var_Append(MAKEFLAGS, value, VAR_GLOBAL);
1373 }
1374 maxJobs = n;
1375 maxJobTokens = maxJobs;
1376 forceJobs = TRUE;
1377 free(value);
1378 }
1379
1380 /*
1381 * Be compatible if user did not specify -j and did not explicitly
1382 * turned compatibility on
1383 */
1384 if (!compatMake && !forceJobs) {
1385 compatMake = TRUE;
1386 }
1387
1388 if (!compatMake)
1389 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1390 if (DEBUG(JOB))
1391 fprintf(debug_file,
1392 "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1393 jp_0, jp_1, maxJobs, maxJobTokens, compatMake ? 1 : 0);
1394
1395 if (!printVars)
1396 Main_ExportMAKEFLAGS(TRUE); /* initial export */
1397
1398
1399 /*
1400 * For compatibility, look at the directories in the VPATH variable
1401 * and add them to the search path, if the variable is defined. The
1402 * variable's value is in the same format as the PATH envariable, i.e.
1403 * <directory>:<directory>:<directory>...
1404 */
1405 if (Var_Exists("VPATH", VAR_CMD)) {
1406 char *vpath, savec;
1407 /*
1408 * GCC stores string constants in read-only memory, but
1409 * Var_Subst will want to write this thing, so store it
1410 * in an array
1411 */
1412 static char VPATH[] = "${VPATH}";
1413
1414 vpath = Var_Subst(VPATH, VAR_CMD, VARE_WANTRES);
1415 path = vpath;
1416 do {
1417 /* skip to end of directory */
1418 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1419 continue;
1420 /* Save terminator character so know when to stop */
1421 savec = *cp;
1422 *cp = '\0';
1423 /* Add directory to search path */
1424 (void)Dir_AddDir(dirSearchPath, path);
1425 *cp = savec;
1426 path = cp + 1;
1427 } while (savec == ':');
1428 free(vpath);
1429 }
1430
1431 /*
1432 * Now that all search paths have been read for suffixes et al, it's
1433 * time to add the default search path to their lists...
1434 */
1435 Suff_DoPaths();
1436
1437 /*
1438 * Propagate attributes through :: dependency lists.
1439 */
1440 Targ_Propagate();
1441
1442 /* print the initial graph, if the user requested it */
1443 if (DEBUG(GRAPH1))
1444 Targ_PrintGraph(1);
1445
1446 /* print the values of any variables requested by the user */
1447 if (printVars) {
1448 doPrintVars();
1449 outOfDate = FALSE;
1450 } else {
1451 outOfDate = runTargets();
1452 }
1453
1454 #ifdef CLEANUP
1455 Lst_Free(variables);
1456 Lst_Free(makefiles);
1457 Lst_Destroy(create, free);
1458 #endif
1459
1460 /* print the graph now it's been processed if the user requested it */
1461 if (DEBUG(GRAPH2))
1462 Targ_PrintGraph(2);
1463
1464 Trace_Log(MAKEEND, 0);
1465
1466 if (enterFlagObj)
1467 printf("%s: Leaving directory `%s'\n", progname, objdir);
1468 if (enterFlag)
1469 printf("%s: Leaving directory `%s'\n", progname, curdir);
1470
1471 #ifdef USE_META
1472 meta_finish();
1473 #endif
1474 Suff_End();
1475 Targ_End();
1476 Arch_End();
1477 Var_End();
1478 Parse_End();
1479 Dir_End();
1480 Job_End();
1481 Trace_End();
1482
1483 return outOfDate ? 1 : 0;
1484 }
1485
1486 /* Open and parse the given makefile, with all its side effects.
1487 *
1488 * Results:
1489 * 0 if ok. -1 if couldn't open file.
1490 */
1491 static int
1492 ReadMakefile(const char *fname)
1493 {
1494 int fd;
1495 char *name, *path = NULL;
1496
1497 if (!strcmp(fname, "-")) {
1498 Parse_File(NULL /*stdin*/, -1);
1499 Var_Set("MAKEFILE", "", VAR_INTERNAL);
1500 } else {
1501 /* if we've chdir'd, rebuild the path name */
1502 if (strcmp(curdir, objdir) && *fname != '/') {
1503 path = str_concat3(curdir, "/", fname);
1504 fd = open(path, O_RDONLY);
1505 if (fd != -1) {
1506 fname = path;
1507 goto found;
1508 }
1509 free(path);
1510
1511 /* If curdir failed, try objdir (ala .depend) */
1512 path = str_concat3(objdir, "/", fname);
1513 fd = open(path, O_RDONLY);
1514 if (fd != -1) {
1515 fname = path;
1516 goto found;
1517 }
1518 } else {
1519 fd = open(fname, O_RDONLY);
1520 if (fd != -1)
1521 goto found;
1522 }
1523 /* look in -I and system include directories. */
1524 name = Dir_FindFile(fname, parseIncPath);
1525 if (!name)
1526 name = Dir_FindFile(fname,
1527 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1528 if (!name || (fd = open(name, O_RDONLY)) == -1) {
1529 free(name);
1530 free(path);
1531 return -1;
1532 }
1533 fname = name;
1534 /*
1535 * set the MAKEFILE variable desired by System V fans -- the
1536 * placement of the setting here means it gets set to the last
1537 * makefile specified, as it is set by SysV make.
1538 */
1539 found:
1540 if (!doing_depend)
1541 Var_Set("MAKEFILE", fname, VAR_INTERNAL);
1542 Parse_File(fname, fd);
1543 }
1544 free(path);
1545 return 0;
1546 }
1547
1548
1549
1550 /*-
1551 * Cmd_Exec --
1552 * Execute the command in cmd, and return the output of that command
1553 * in a string. In the output, newlines are replaced with spaces.
1554 *
1555 * Results:
1556 * A string containing the output of the command, or the empty string.
1557 * *errfmt returns a format string describing the command failure,
1558 * if any, using a single %s conversion specification.
1559 *
1560 * Side Effects:
1561 * The string must be freed by the caller.
1562 */
1563 char *
1564 Cmd_Exec(const char *cmd, const char **errfmt)
1565 {
1566 const char *args[4]; /* Args for invoking the shell */
1567 int fds[2]; /* Pipe streams */
1568 int cpid; /* Child PID */
1569 int pid; /* PID from wait() */
1570 int status; /* command exit status */
1571 Buffer buf; /* buffer to store the result */
1572 ssize_t bytes_read;
1573 char *res; /* result */
1574 size_t res_len;
1575 char *cp;
1576 int savederr; /* saved errno */
1577
1578 *errfmt = NULL;
1579
1580 if (!shellName)
1581 Shell_Init();
1582 /*
1583 * Set up arguments for shell
1584 */
1585 args[0] = shellName;
1586 args[1] = "-c";
1587 args[2] = cmd;
1588 args[3] = NULL;
1589
1590 /*
1591 * Open a pipe for fetching its output
1592 */
1593 if (pipe(fds) == -1) {
1594 *errfmt = "Couldn't create pipe for \"%s\"";
1595 goto bad;
1596 }
1597
1598 /*
1599 * Fork
1600 */
1601 switch (cpid = vFork()) {
1602 case 0:
1603 /*
1604 * Close input side of pipe
1605 */
1606 (void)close(fds[0]);
1607
1608 /*
1609 * Duplicate the output stream to the shell's output, then
1610 * shut the extra thing down. Note we don't fetch the error
1611 * stream...why not? Why?
1612 */
1613 (void)dup2(fds[1], 1);
1614 (void)close(fds[1]);
1615
1616 Var_ExportVars();
1617
1618 (void)execv(shellPath, UNCONST(args));
1619 _exit(1);
1620 /*NOTREACHED*/
1621
1622 case -1:
1623 *errfmt = "Couldn't exec \"%s\"";
1624 goto bad;
1625
1626 default:
1627 /*
1628 * No need for the writing half
1629 */
1630 (void)close(fds[1]);
1631
1632 savederr = 0;
1633 Buf_Init(&buf, 0);
1634
1635 do {
1636 char result[BUFSIZ];
1637 bytes_read = read(fds[0], result, sizeof(result));
1638 if (bytes_read > 0)
1639 Buf_AddBytes(&buf, result, (size_t)bytes_read);
1640 }
1641 while (bytes_read > 0 || (bytes_read == -1 && errno == EINTR));
1642 if (bytes_read == -1)
1643 savederr = errno;
1644
1645 /*
1646 * Close the input side of the pipe.
1647 */
1648 (void)close(fds[0]);
1649
1650 /*
1651 * Wait for the process to exit.
1652 */
1653 while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) {
1654 JobReapChild(pid, status, FALSE);
1655 continue;
1656 }
1657 res_len = Buf_Size(&buf);
1658 res = Buf_Destroy(&buf, FALSE);
1659
1660 if (savederr != 0)
1661 *errfmt = "Couldn't read shell's output for \"%s\"";
1662
1663 if (WIFSIGNALED(status))
1664 *errfmt = "\"%s\" exited on a signal";
1665 else if (WEXITSTATUS(status) != 0)
1666 *errfmt = "\"%s\" returned non-zero status";
1667
1668 /* Convert newlines to spaces. A final newline is just stripped */
1669 if (res_len > 0 && res[res_len - 1] == '\n')
1670 res[res_len - 1] = '\0';
1671 for (cp = res; *cp != '\0'; cp++)
1672 if (*cp == '\n')
1673 *cp = ' ';
1674 break;
1675 }
1676 return res;
1677 bad:
1678 return bmake_strdup("");
1679 }
1680
1681 /*-
1682 * Error --
1683 * Print an error message given its format.
1684 *
1685 * Results:
1686 * None.
1687 *
1688 * Side Effects:
1689 * The message is printed.
1690 */
1691 void
1692 Error(const char *fmt, ...)
1693 {
1694 va_list ap;
1695 FILE *err_file;
1696
1697 err_file = debug_file;
1698 if (err_file == stdout)
1699 err_file = stderr;
1700 (void)fflush(stdout);
1701 for (;;) {
1702 va_start(ap, fmt);
1703 fprintf(err_file, "%s: ", progname);
1704 (void)vfprintf(err_file, fmt, ap);
1705 va_end(ap);
1706 (void)fprintf(err_file, "\n");
1707 (void)fflush(err_file);
1708 if (err_file == stderr)
1709 break;
1710 err_file = stderr;
1711 }
1712 }
1713
1714 /* Produce a Fatal error message, then exit immediately.
1715 *
1716 * If jobs are running, waits for them to finish. */
1717 void
1718 Fatal(const char *fmt, ...)
1719 {
1720 va_list ap;
1721
1722 va_start(ap, fmt);
1723 if (jobsRunning)
1724 Job_Wait();
1725
1726 (void)fflush(stdout);
1727 (void)vfprintf(stderr, fmt, ap);
1728 va_end(ap);
1729 (void)fprintf(stderr, "\n");
1730 (void)fflush(stderr);
1731
1732 PrintOnError(NULL, NULL);
1733
1734 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1735 Targ_PrintGraph(2);
1736 Trace_Log(MAKEERROR, 0);
1737 exit(2); /* Not 1 so -q can distinguish error */
1738 }
1739
1740 /*
1741 * Punt --
1742 * Major exception once jobs are being created. Kills all jobs, prints
1743 * a message and exits.
1744 *
1745 * Results:
1746 * None
1747 *
1748 * Side Effects:
1749 * All children are killed indiscriminately and the program Lib_Exits
1750 */
1751 void
1752 Punt(const char *fmt, ...)
1753 {
1754 va_list ap;
1755
1756 va_start(ap, fmt);
1757 (void)fflush(stdout);
1758 (void)fprintf(stderr, "%s: ", progname);
1759 (void)vfprintf(stderr, fmt, ap);
1760 va_end(ap);
1761 (void)fprintf(stderr, "\n");
1762 (void)fflush(stderr);
1763
1764 PrintOnError(NULL, NULL);
1765
1766 DieHorribly();
1767 }
1768
1769 /*-
1770 * DieHorribly --
1771 * Exit without giving a message.
1772 *
1773 * Results:
1774 * None
1775 *
1776 * Side Effects:
1777 * A big one...
1778 */
1779 void
1780 DieHorribly(void)
1781 {
1782 if (jobsRunning)
1783 Job_AbortAll();
1784 if (DEBUG(GRAPH2))
1785 Targ_PrintGraph(2);
1786 Trace_Log(MAKEERROR, 0);
1787 exit(2); /* Not 1, so -q can distinguish error */
1788 }
1789
1790 /*
1791 * Finish --
1792 * Called when aborting due to errors in child shell to signal
1793 * abnormal exit.
1794 *
1795 * Results:
1796 * None
1797 *
1798 * Side Effects:
1799 * The program exits
1800 */
1801 void
1802 Finish(int errors)
1803 /* number of errors encountered in Make_Make */
1804 {
1805 if (dieQuietly(NULL, -1))
1806 exit(2);
1807 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1808 }
1809
1810 /*
1811 * eunlink --
1812 * Remove a file carefully, avoiding directories.
1813 */
1814 int
1815 eunlink(const char *file)
1816 {
1817 struct stat st;
1818
1819 if (lstat(file, &st) == -1)
1820 return -1;
1821
1822 if (S_ISDIR(st.st_mode)) {
1823 errno = EISDIR;
1824 return -1;
1825 }
1826 return unlink(file);
1827 }
1828
1829 /*
1830 * execError --
1831 * Print why exec failed, avoiding stdio.
1832 */
1833 void
1834 execError(const char *af, const char *av)
1835 {
1836 #ifdef USE_IOVEC
1837 int i = 0;
1838 struct iovec iov[8];
1839 #define IOADD(s) \
1840 (void)(iov[i].iov_base = UNCONST(s), \
1841 iov[i].iov_len = strlen(iov[i].iov_base), \
1842 i++)
1843 #else
1844 #define IOADD(void)write(2, s, strlen(s))
1845 #endif
1846
1847 IOADD(progname);
1848 IOADD(": ");
1849 IOADD(af);
1850 IOADD("(");
1851 IOADD(av);
1852 IOADD(") failed (");
1853 IOADD(strerror(errno));
1854 IOADD(")\n");
1855
1856 #ifdef USE_IOVEC
1857 while (writev(2, iov, 8) == -1 && errno == EAGAIN)
1858 continue;
1859 #endif
1860 }
1861
1862 /*
1863 * usage --
1864 * exit with usage message
1865 */
1866 static void
1867 usage(void)
1868 {
1869 char *p;
1870 if ((p = strchr(progname, '[')) != NULL)
1871 *p = '\0';
1872
1873 (void)fprintf(stderr,
1874 "usage: %s [-BeikNnqrstWwX] \n"
1875 " [-C directory] [-D variable] [-d flags] [-f makefile]\n"
1876 " [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n"
1877 " [-V variable] [-v variable] [variable=value] [target ...]\n",
1878 progname);
1879 exit(2);
1880 }
1881
1882 /*
1883 * realpath(3) can get expensive, cache results...
1884 */
1885 static GNode *cached_realpaths = NULL;
1886
1887 static GNode *
1888 get_cached_realpaths(void)
1889 {
1890
1891 if (!cached_realpaths) {
1892 cached_realpaths = Targ_NewGN("Realpath");
1893 #ifndef DEBUG_REALPATH_CACHE
1894 cached_realpaths->flags = INTERNAL;
1895 #endif
1896 }
1897
1898 return cached_realpaths;
1899 }
1900
1901 /* purge any relative paths */
1902 static void
1903 purge_cached_realpaths(void)
1904 {
1905 GNode *cache = get_cached_realpaths();
1906 Hash_Entry *he, *nhe;
1907 Hash_Search hs;
1908
1909 he = Hash_EnumFirst(&cache->context, &hs);
1910 while (he) {
1911 nhe = Hash_EnumNext(&hs);
1912 if (he->name[0] != '/') {
1913 if (DEBUG(DIR))
1914 fprintf(stderr, "cached_realpath: purging %s\n", he->name);
1915 Hash_DeleteEntry(&cache->context, he);
1916 }
1917 he = nhe;
1918 }
1919 }
1920
1921 char *
1922 cached_realpath(const char *pathname, char *resolved)
1923 {
1924 GNode *cache;
1925 const char *rp;
1926 char *cp;
1927
1928 if (!pathname || !pathname[0])
1929 return NULL;
1930
1931 cache = get_cached_realpaths();
1932
1933 if ((rp = Var_Value(pathname, cache, &cp)) != NULL) {
1934 /* a hit */
1935 strncpy(resolved, rp, MAXPATHLEN);
1936 resolved[MAXPATHLEN - 1] = '\0';
1937 } else if ((rp = realpath(pathname, resolved)) != NULL) {
1938 Var_Set(pathname, rp, cache);
1939 } /* else should we negative-cache? */
1940
1941 bmake_free(cp);
1942 return rp ? resolved : NULL;
1943 }
1944
1945
1946 static int
1947 addErrorCMD(void *cmdp, void *gnp)
1948 {
1949 if (cmdp == NULL)
1950 return 1; /* stop */
1951 Var_Append(".ERROR_CMD", cmdp, VAR_GLOBAL);
1952 return 0;
1953 }
1954
1955 /*
1956 * Return true if we should die without noise.
1957 * For example our failing child was a sub-make
1958 * or failure happend elsewhere.
1959 */
1960 int
1961 dieQuietly(GNode *gn, int bf)
1962 {
1963 static int quietly = -1;
1964
1965 if (quietly < 0) {
1966 if (DEBUG(JOB) || getBoolean(".MAKE.DIE_QUIETLY", 1) == 0)
1967 quietly = 0;
1968 else if (bf >= 0)
1969 quietly = bf;
1970 else
1971 quietly = (gn) ? ((gn->type & (OP_MAKE)) != 0) : 0;
1972 }
1973 return quietly;
1974 }
1975
1976 void
1977 PrintOnError(GNode *gn, const char *s)
1978 {
1979 static GNode *en = NULL;
1980 const char *expr;
1981 char *cp;
1982
1983 if (DEBUG(HASH)) {
1984 Targ_Stats();
1985 Var_Stats();
1986 }
1987
1988 /* we generally want to keep quiet if a sub-make died */
1989 if (dieQuietly(gn, -1))
1990 return;
1991
1992 if (s)
1993 printf("%s", s);
1994
1995 printf("\n%s: stopped in %s\n", progname, curdir);
1996
1997 if (en)
1998 return; /* we've been here! */
1999 if (gn) {
2000 /*
2001 * We can print this even if there is no .ERROR target.
2002 */
2003 Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL);
2004 Var_Delete(".ERROR_CMD", VAR_GLOBAL);
2005 Lst_ForEach(gn->commands, addErrorCMD, gn);
2006 }
2007 expr = "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}";
2008 cp = Var_Subst(expr, VAR_GLOBAL, VARE_WANTRES);
2009 printf("%s", cp);
2010 free(cp);
2011 fflush(stdout);
2012
2013 /*
2014 * Finally, see if there is a .ERROR target, and run it if so.
2015 */
2016 en = Targ_FindNode(".ERROR", TARG_NOCREATE);
2017 if (en) {
2018 en->type |= OP_SPECIAL;
2019 Compat_Make(en, en);
2020 }
2021 }
2022
2023 void
2024 Main_ExportMAKEFLAGS(Boolean first)
2025 {
2026 static Boolean once = TRUE;
2027 const char *expr;
2028 char *s;
2029
2030 if (once != first)
2031 return;
2032 once = FALSE;
2033
2034 expr = "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}";
2035 s = Var_Subst(expr, VAR_CMD, VARE_WANTRES);
2036 if (s[0] != '\0') {
2037 #ifdef POSIX
2038 setenv("MAKEFLAGS", s, 1);
2039 #else
2040 setenv("MAKE", s, 1);
2041 #endif
2042 }
2043 }
2044
2045 char *
2046 getTmpdir(void)
2047 {
2048 static char *tmpdir = NULL;
2049
2050 if (!tmpdir) {
2051 struct stat st;
2052
2053 /*
2054 * Honor $TMPDIR but only if it is valid.
2055 * Ensure it ends with /.
2056 */
2057 tmpdir = Var_Subst("${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL,
2058 VARE_WANTRES);
2059 if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
2060 free(tmpdir);
2061 tmpdir = bmake_strdup(_PATH_TMP);
2062 }
2063 }
2064 return tmpdir;
2065 }
2066
2067 /*
2068 * Create and open a temp file using "pattern".
2069 * If "fnamep" is provided set it to a copy of the filename created.
2070 * Otherwise unlink the file once open.
2071 */
2072 int
2073 mkTempFile(const char *pattern, char **fnamep)
2074 {
2075 static char *tmpdir = NULL;
2076 char tfile[MAXPATHLEN];
2077 int fd;
2078
2079 if (!pattern)
2080 pattern = TMPPAT;
2081 if (!tmpdir)
2082 tmpdir = getTmpdir();
2083 if (pattern[0] == '/') {
2084 snprintf(tfile, sizeof(tfile), "%s", pattern);
2085 } else {
2086 snprintf(tfile, sizeof(tfile), "%s%s", tmpdir, pattern);
2087 }
2088 if ((fd = mkstemp(tfile)) < 0)
2089 Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
2090 if (fnamep) {
2091 *fnamep = bmake_strdup(tfile);
2092 } else {
2093 unlink(tfile); /* we just want the descriptor */
2094 }
2095 return fd;
2096 }
2097
2098 /*
2099 * Convert a string representation of a boolean.
2100 * Anything that looks like "No", "False", "Off", "0" etc,
2101 * is FALSE, otherwise TRUE.
2102 */
2103 Boolean
2104 s2Boolean(const char *s, Boolean bf)
2105 {
2106 if (s) {
2107 switch(*s) {
2108 case '\0': /* not set - the default wins */
2109 break;
2110 case '0':
2111 case 'F':
2112 case 'f':
2113 case 'N':
2114 case 'n':
2115 bf = FALSE;
2116 break;
2117 case 'O':
2118 case 'o':
2119 switch (s[1]) {
2120 case 'F':
2121 case 'f':
2122 bf = FALSE;
2123 break;
2124 default:
2125 bf = TRUE;
2126 break;
2127 }
2128 break;
2129 default:
2130 bf = TRUE;
2131 break;
2132 }
2133 }
2134 return bf;
2135 }
2136
2137 /*
2138 * Return a Boolean based on setting of a knob.
2139 *
2140 * If the knob is not set, the supplied default is the return value.
2141 * If set, anything that looks or smells like "No", "False", "Off", "0" etc,
2142 * is FALSE, otherwise TRUE.
2143 */
2144 Boolean
2145 getBoolean(const char *name, Boolean fallback)
2146 {
2147 char *expr = str_concat3("${", name, ":U:tl}");
2148 char *value = Var_Subst(expr, VAR_GLOBAL, VARE_WANTRES);
2149 Boolean res = s2Boolean(value, fallback);
2150 free(value);
2151 free(expr);
2152 return res;
2153 }
2154