mandoc: update to 1.14.1
[unleashed.git] / bin / bmake / main.c
blob1ba4a55d2c0082bc14c1e4dffcb7008b8fdf1d8f
1 /* $NetBSD: main.c,v 1.255 2017/01/31 06:54:23 sjg Exp $ */
3 /*
4 * Copyright (c) 1988, 1989, 1990, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Adam de Boor.
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.
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.
36 * Copyright (c) 1989 by Berkeley Softworks
37 * All rights reserved.
39 * This code is derived from software contributed to Berkeley by
40 * Adam de Boor.
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.
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.
71 #ifndef MAKE_NATIVE
72 static char rcsid[] = "$NetBSD: main.c,v 1.255 2017/01/31 06:54:23 sjg Exp $";
73 #else
74 #include <sys/cdefs.h>
75 #ifndef lint
76 __COPYRIGHT("@(#) Copyright (c) 1988, 1989, 1990, 1993\
77 The Regents of the University of California. All rights reserved.");
78 #endif /* not lint */
80 #ifndef lint
81 #if 0
82 static char sccsid[] = "@(#)main.c 8.3 (Berkeley) 3/19/94";
83 #else
84 __RCSID("$NetBSD: main.c,v 1.255 2017/01/31 06:54:23 sjg Exp $");
85 #endif
86 #endif /* not lint */
87 #endif
89 /*-
90 * main.c --
91 * The main file for this entire program. Exit routines etc
92 * reside here.
94 * Utility functions defined in this file:
95 * Main_ParseArgLine Takes a line of arguments, breaks them and
96 * treats them as if they were given when first
97 * invoked. Used by the parse module to implement
98 * the .MFLAGS target.
100 * Error Print a tagged error message. The global
101 * MAKE variable must have been defined. This
102 * takes a format string and optional arguments
103 * for it.
105 * Fatal Print an error message and exit. Also takes
106 * a format string and arguments for it.
108 * Punt Aborts all jobs and exits with a message. Also
109 * takes a format string and arguments for it.
111 * Finish Finish things up by printing the number of
112 * errors which occurred, as passed to it, and
113 * exiting.
116 #include <sys/types.h>
117 #include <sys/time.h>
118 #include <sys/param.h>
119 #include <sys/resource.h>
120 #include <sys/stat.h>
121 #if defined(MAKE_NATIVE) && defined(HAVE_SYSCTL)
122 #include <sys/sysctl.h>
123 #endif
124 #include <sys/utsname.h>
125 #include "wait.h"
127 #include <errno.h>
128 #include <signal.h>
129 #include <stdarg.h>
130 #include <stdio.h>
131 #include <stdlib.h>
132 #include <time.h>
133 #include <ctype.h>
135 #include "make.h"
136 #include "hash.h"
137 #include "dir.h"
138 #include "job.h"
139 #include "pathnames.h"
140 #include "trace.h"
142 #ifdef USE_IOVEC
143 #include <sys/uio.h>
144 #endif
146 #ifndef DEFMAXLOCAL
147 #define DEFMAXLOCAL DEFMAXJOBS
148 #endif /* DEFMAXLOCAL */
150 #ifndef __arraycount
151 # define __arraycount(__x) (sizeof(__x) / sizeof(__x[0]))
152 #endif
154 Lst create; /* Targets to be made */
155 time_t now; /* Time at start of make */
156 GNode *DEFAULT; /* .DEFAULT node */
157 Boolean allPrecious; /* .PRECIOUS given on line by itself */
158 Boolean deleteOnError; /* .DELETE_ON_ERROR: set */
160 static Boolean noBuiltins; /* -r flag */
161 static Lst makefiles; /* ordered list of makefiles to read */
162 static Boolean printVars; /* print value of one or more vars */
163 static Lst variables; /* list of variables to print */
164 int maxJobs; /* -j argument */
165 static int maxJobTokens; /* -j argument */
166 Boolean compatMake; /* -B argument */
167 int debug; /* -d argument */
168 Boolean debugVflag; /* -dV */
169 Boolean noExecute; /* -n flag */
170 Boolean noRecursiveExecute; /* -N flag */
171 Boolean keepgoing; /* -k flag */
172 Boolean queryFlag; /* -q flag */
173 Boolean touchFlag; /* -t flag */
174 Boolean enterFlag; /* -w flag */
175 Boolean enterFlagObj; /* -w and objdir != srcdir */
176 Boolean ignoreErrors; /* -i flag */
177 Boolean beSilent; /* -s flag */
178 Boolean oldVars; /* variable substitution style */
179 Boolean checkEnvFirst; /* -e flag */
180 Boolean parseWarnFatal; /* -W flag */
181 Boolean jobServer; /* -J flag */
182 static int jp_0 = -1, jp_1 = -1; /* ends of parent job pipe */
183 Boolean varNoExportEnv; /* -X flag */
184 Boolean doing_depend; /* Set while reading .depend */
185 static Boolean jobsRunning; /* TRUE if the jobs might be running */
186 static const char * tracefile;
187 static void MainParseArgs(int, char **);
188 static int ReadMakefile(const void *, const void *);
189 static void usage(void) MAKE_ATTR_DEAD;
191 static Boolean ignorePWD; /* if we use -C, PWD is meaningless */
192 static char objdir[MAXPATHLEN + 1]; /* where we chdir'ed to */
193 char curdir[MAXPATHLEN + 1]; /* Startup directory */
194 char *progname; /* the program name */
195 char *makeDependfile;
196 pid_t myPid;
197 int makelevel;
199 Boolean forceJobs = FALSE;
202 * On some systems MACHINE is defined as something other than
203 * what we want.
205 #ifdef FORCE_MACHINE
206 # undef MACHINE
207 # define MACHINE FORCE_MACHINE
208 #endif
210 extern Lst parseIncPath;
213 * For compatibility with the POSIX version of MAKEFLAGS that includes
214 * all the options with out -, convert flags to -f -l -a -g -s.
216 static char *
217 explode(const char *flags)
219 size_t len;
220 char *nf, *st;
221 const char *f;
223 if (flags == NULL)
224 return NULL;
226 for (f = flags; *f; f++)
227 if (!isalpha((unsigned char)*f))
228 break;
230 if (*f)
231 return bmake_strdup(flags);
233 len = strlen(flags);
234 st = nf = bmake_malloc(len * 3 + 1);
235 while (*flags) {
236 *nf++ = '-';
237 *nf++ = *flags++;
238 *nf++ = ' ';
240 *nf = '\0';
241 return st;
244 static void
245 parse_debug_options(const char *argvalue)
247 const char *modules;
248 const char *mode;
249 char *fname;
250 int len;
252 for (modules = argvalue; *modules; ++modules) {
253 switch (*modules) {
254 case 'A':
255 debug = ~0;
256 break;
257 case 'a':
258 debug |= DEBUG_ARCH;
259 break;
260 case 'C':
261 debug |= DEBUG_CWD;
262 break;
263 case 'c':
264 debug |= DEBUG_COND;
265 break;
266 case 'd':
267 debug |= DEBUG_DIR;
268 break;
269 case 'e':
270 debug |= DEBUG_ERROR;
271 break;
272 case 'f':
273 debug |= DEBUG_FOR;
274 break;
275 case 'g':
276 if (modules[1] == '1') {
277 debug |= DEBUG_GRAPH1;
278 ++modules;
280 else if (modules[1] == '2') {
281 debug |= DEBUG_GRAPH2;
282 ++modules;
284 else if (modules[1] == '3') {
285 debug |= DEBUG_GRAPH3;
286 ++modules;
288 break;
289 case 'j':
290 debug |= DEBUG_JOB;
291 break;
292 case 'l':
293 debug |= DEBUG_LOUD;
294 break;
295 case 'M':
296 debug |= DEBUG_META;
297 break;
298 case 'm':
299 debug |= DEBUG_MAKE;
300 break;
301 case 'n':
302 debug |= DEBUG_SCRIPT;
303 break;
304 case 'p':
305 debug |= DEBUG_PARSE;
306 break;
307 case 's':
308 debug |= DEBUG_SUFF;
309 break;
310 case 't':
311 debug |= DEBUG_TARG;
312 break;
313 case 'V':
314 debugVflag = TRUE;
315 break;
316 case 'v':
317 debug |= DEBUG_VAR;
318 break;
319 case 'x':
320 debug |= DEBUG_SHELL;
321 break;
322 case 'F':
323 if (debug_file != stdout && debug_file != stderr)
324 fclose(debug_file);
325 if (*++modules == '+') {
326 modules++;
327 mode = "a";
328 } else
329 mode = "w";
330 if (strcmp(modules, "stdout") == 0) {
331 debug_file = stdout;
332 goto debug_setbuf;
334 if (strcmp(modules, "stderr") == 0) {
335 debug_file = stderr;
336 goto debug_setbuf;
338 len = strlen(modules);
339 fname = malloc(len + 20);
340 memcpy(fname, modules, len + 1);
341 /* Let the filename be modified by the pid */
342 if (strcmp(fname + len - 3, ".%d") == 0)
343 snprintf(fname + len - 2, 20, "%d", getpid());
344 debug_file = fopen(fname, mode);
345 if (!debug_file) {
346 fprintf(stderr, "Cannot open debug file %s\n",
347 fname);
348 usage();
350 free(fname);
351 goto debug_setbuf;
352 default:
353 (void)fprintf(stderr,
354 "%s: illegal argument to d option -- %c\n",
355 progname, *modules);
356 usage();
359 debug_setbuf:
361 * Make the debug_file unbuffered, and make
362 * stdout line buffered (unless debugfile == stdout).
364 setvbuf(debug_file, NULL, _IONBF, 0);
365 if (debug_file != stdout) {
366 setvbuf(stdout, NULL, _IOLBF, 0);
371 * MainParseArgs --
372 * Parse a given argument vector. Called from main() and from
373 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
375 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
377 * Results:
378 * None
380 * Side Effects:
381 * Various global and local flags will be set depending on the flags
382 * given
384 static void
385 MainParseArgs(int argc, char **argv)
387 char *p;
388 int c = '?';
389 int arginc;
390 char *argvalue;
391 const char *getopt_def;
392 char *optscan;
393 Boolean inOption, dashDash = FALSE;
394 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
396 #define OPTFLAGS "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrstw"
397 /* Can't actually use getopt(3) because rescanning is not portable */
399 getopt_def = OPTFLAGS;
400 rearg:
401 inOption = FALSE;
402 optscan = NULL;
403 while(argc > 1) {
404 char *getopt_spec;
405 if(!inOption)
406 optscan = argv[1];
407 c = *optscan++;
408 arginc = 0;
409 if(inOption) {
410 if(c == '\0') {
411 ++argv;
412 --argc;
413 inOption = FALSE;
414 continue;
416 } else {
417 if (c != '-' || dashDash)
418 break;
419 inOption = TRUE;
420 c = *optscan++;
422 /* '-' found at some earlier point */
423 getopt_spec = strchr(getopt_def, c);
424 if(c != '\0' && getopt_spec != NULL && getopt_spec[1] == ':') {
425 /* -<something> found, and <something> should have an arg */
426 inOption = FALSE;
427 arginc = 1;
428 argvalue = optscan;
429 if(*argvalue == '\0') {
430 if (argc < 3)
431 goto noarg;
432 argvalue = argv[2];
433 arginc = 2;
435 } else {
436 argvalue = NULL;
438 switch(c) {
439 case '\0':
440 arginc = 1;
441 inOption = FALSE;
442 break;
443 case 'B':
444 compatMake = TRUE;
445 Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
446 Var_Set(MAKE_MODE, "compat", VAR_GLOBAL, 0);
447 break;
448 case 'C':
449 if (chdir(argvalue) == -1) {
450 (void)fprintf(stderr,
451 "%s: chdir %s: %s\n",
452 progname, argvalue,
453 strerror(errno));
454 exit(1);
456 if (getcwd(curdir, MAXPATHLEN) == NULL) {
457 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
458 exit(2);
460 ignorePWD = TRUE;
461 break;
462 case 'D':
463 if (argvalue == NULL || argvalue[0] == 0) goto noarg;
464 Var_Set(argvalue, "1", VAR_GLOBAL, 0);
465 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
466 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
467 break;
468 case 'I':
469 if (argvalue == NULL) goto noarg;
470 Parse_AddIncludeDir(argvalue);
471 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
472 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
473 break;
474 case 'J':
475 if (argvalue == NULL) goto noarg;
476 if (sscanf(argvalue, "%d,%d", &jp_0, &jp_1) != 2) {
477 (void)fprintf(stderr,
478 "%s: internal error -- J option malformed (%s)\n",
479 progname, argvalue);
480 usage();
482 if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
483 (fcntl(jp_1, F_GETFD, 0) < 0)) {
484 #if 0
485 (void)fprintf(stderr,
486 "%s: ###### warning -- J descriptors were closed!\n",
487 progname);
488 exit(2);
489 #endif
490 jp_0 = -1;
491 jp_1 = -1;
492 compatMake = TRUE;
493 } else {
494 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
495 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
496 jobServer = TRUE;
498 break;
499 case 'N':
500 noExecute = TRUE;
501 noRecursiveExecute = TRUE;
502 Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
503 break;
504 case 'S':
505 keepgoing = FALSE;
506 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
507 break;
508 case 'T':
509 if (argvalue == NULL) goto noarg;
510 tracefile = bmake_strdup(argvalue);
511 Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
512 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
513 break;
514 case 'V':
515 if (argvalue == NULL) goto noarg;
516 printVars = TRUE;
517 (void)Lst_AtEnd(variables, argvalue);
518 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
519 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
520 break;
521 case 'W':
522 parseWarnFatal = TRUE;
523 break;
524 case 'X':
525 varNoExportEnv = TRUE;
526 Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
527 break;
528 case 'd':
529 if (argvalue == NULL) goto noarg;
530 /* If '-d-opts' don't pass to children */
531 if (argvalue[0] == '-')
532 argvalue++;
533 else {
534 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
535 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
537 parse_debug_options(argvalue);
538 break;
539 case 'e':
540 checkEnvFirst = TRUE;
541 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
542 break;
543 case 'f':
544 if (argvalue == NULL) goto noarg;
545 (void)Lst_AtEnd(makefiles, argvalue);
546 break;
547 case 'i':
548 ignoreErrors = TRUE;
549 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
550 break;
551 case 'j':
552 if (argvalue == NULL) goto noarg;
553 forceJobs = TRUE;
554 maxJobs = strtol(argvalue, &p, 0);
555 if (*p != '\0' || maxJobs < 1) {
556 (void)fprintf(stderr, "%s: illegal argument to -j -- must be positive integer!\n",
557 progname);
558 exit(1);
560 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
561 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
562 Var_Set(".MAKE.JOBS", argvalue, VAR_GLOBAL, 0);
563 maxJobTokens = maxJobs;
564 break;
565 case 'k':
566 keepgoing = TRUE;
567 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
568 break;
569 case 'm':
570 if (argvalue == NULL) goto noarg;
571 /* look for magic parent directory search string */
572 if (strncmp(".../", argvalue, 4) == 0) {
573 if (!Dir_FindHereOrAbove(curdir, argvalue+4,
574 found_path, sizeof(found_path)))
575 break; /* nothing doing */
576 (void)Dir_AddDir(sysIncPath, found_path);
577 } else {
578 (void)Dir_AddDir(sysIncPath, argvalue);
580 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
581 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
582 break;
583 case 'n':
584 noExecute = TRUE;
585 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
586 break;
587 case 'q':
588 queryFlag = TRUE;
589 /* Kind of nonsensical, wot? */
590 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
591 break;
592 case 'r':
593 noBuiltins = TRUE;
594 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
595 break;
596 case 's':
597 beSilent = TRUE;
598 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
599 break;
600 case 't':
601 touchFlag = TRUE;
602 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
603 break;
604 case 'w':
605 enterFlag = TRUE;
606 Var_Append(MAKEFLAGS, "-w", VAR_GLOBAL);
607 break;
608 case '-':
609 dashDash = TRUE;
610 break;
611 default:
612 case '?':
613 #ifndef MAKE_NATIVE
614 fprintf(stderr, "getopt(%s) -> %d (%c)\n",
615 OPTFLAGS, c, c);
616 #endif
617 usage();
619 argv += arginc;
620 argc -= arginc;
623 oldVars = TRUE;
626 * See if the rest of the arguments are variable assignments and
627 * perform them if so. Else take them to be targets and stuff them
628 * on the end of the "create" list.
630 for (; argc > 1; ++argv, --argc)
631 if (Parse_IsVar(argv[1])) {
632 Parse_DoVar(argv[1], VAR_CMD);
633 } else {
634 if (!*argv[1])
635 Punt("illegal (null) argument.");
636 if (*argv[1] == '-' && !dashDash)
637 goto rearg;
638 (void)Lst_AtEnd(create, bmake_strdup(argv[1]));
641 return;
642 noarg:
643 (void)fprintf(stderr, "%s: option requires an argument -- %c\n",
644 progname, c);
645 usage();
649 * Main_ParseArgLine --
650 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
651 * is encountered and by main() when reading the .MAKEFLAGS envariable.
652 * Takes a line of arguments and breaks it into its
653 * component words and passes those words and the number of them to the
654 * MainParseArgs function.
655 * The line should have all its leading whitespace removed.
657 * Input:
658 * line Line to fracture
660 * Results:
661 * None
663 * Side Effects:
664 * Only those that come from the various arguments.
666 void
667 Main_ParseArgLine(const char *line)
669 char **argv; /* Manufactured argument vector */
670 int argc; /* Number of arguments in argv */
671 char *args; /* Space used by the args */
672 char *buf, *p1;
673 char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
674 size_t len;
676 if (line == NULL)
677 return;
678 for (; *line == ' '; ++line)
679 continue;
680 if (!*line)
681 return;
683 #ifndef POSIX
686 * $MAKE may simply be naming the make(1) binary
688 char *cp;
690 if (!(cp = strrchr(line, '/')))
691 cp = line;
692 if ((cp = strstr(cp, "make")) &&
693 strcmp(cp, "make") == 0)
694 return;
696 #endif
697 buf = bmake_malloc(len = strlen(line) + strlen(argv0) + 2);
698 (void)snprintf(buf, len, "%s %s", argv0, line);
699 free(p1);
701 argv = brk_string(buf, &argc, TRUE, &args);
702 if (argv == NULL) {
703 Error("Unterminated quoted string [%s]", buf);
704 free(buf);
705 return;
707 free(buf);
708 MainParseArgs(argc, argv);
710 free(args);
711 free(argv);
714 Boolean
715 Main_SetObjdir(const char *fmt, ...)
717 struct stat sb;
718 char *p, *path;
719 char buf[MAXPATHLEN + 1], pbuf[MAXPATHLEN + 1];
720 Boolean rc = FALSE;
721 va_list ap;
723 va_start(ap, fmt);
724 vsnprintf(path = pbuf, MAXPATHLEN, fmt, ap);
725 va_end(ap);
727 /* expand variable substitutions */
728 if (strchr(path, '$') != 0) {
729 snprintf(buf, MAXPATHLEN, "%s", path);
730 path = p = Var_Subst(NULL, buf, VAR_GLOBAL, VARF_WANTRES);
731 } else
732 p = NULL;
734 if (path[0] != '/') {
735 snprintf(buf, MAXPATHLEN, "%s/%s", curdir, path);
736 path = buf;
739 /* look for the directory and try to chdir there */
740 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
741 if (chdir(path)) {
742 (void)fprintf(stderr, "make warning: %s: %s.\n",
743 path, strerror(errno));
744 } else {
745 strncpy(objdir, path, MAXPATHLEN);
746 Var_Set(".OBJDIR", objdir, VAR_GLOBAL, 0);
747 setenv("PWD", objdir, 1);
748 Dir_InitDot();
749 rc = TRUE;
750 if (enterFlag && strcmp(objdir, curdir) != 0)
751 enterFlagObj = TRUE;
755 free(p);
756 return rc;
759 static Boolean
760 Main_SetVarObjdir(const char *var, const char *suffix)
762 char *p1, *path;
763 if ((path = Var_Value(var, VAR_CMD, &p1)) == NULL)
764 return FALSE;
766 (void)Main_SetObjdir("%s%s", path, suffix);
767 free(p1);
768 return TRUE;
772 * ReadAllMakefiles --
773 * wrapper around ReadMakefile() to read all.
775 * Results:
776 * TRUE if ok, FALSE on error
778 static int
779 ReadAllMakefiles(const void *p, const void *q)
781 return (ReadMakefile(p, q) == 0);
785 str2Lst_Append(Lst lp, char *str, const char *sep)
787 char *cp;
788 int n;
790 if (!sep)
791 sep = " \t";
793 for (n = 0, cp = strtok(str, sep); cp; cp = strtok(NULL, sep)) {
794 (void)Lst_AtEnd(lp, cp);
795 n++;
797 return (n);
800 #ifdef SIGINFO
801 /*ARGSUSED*/
802 static void
803 siginfo(int signo MAKE_ATTR_UNUSED)
805 char dir[MAXPATHLEN];
806 char str[2 * MAXPATHLEN];
807 int len;
808 if (getcwd(dir, sizeof(dir)) == NULL)
809 return;
810 len = snprintf(str, sizeof(str), "%s: Working in: %s\n", progname, dir);
811 if (len > 0)
812 (void)write(STDERR_FILENO, str, (size_t)len);
814 #endif
817 * Allow makefiles some control over the mode we run in.
819 void
820 MakeMode(const char *mode)
822 char *mp = NULL;
824 if (!mode)
825 mode = mp = Var_Subst(NULL, "${" MAKE_MODE ":tl}",
826 VAR_GLOBAL, VARF_WANTRES);
828 if (mode && *mode) {
829 if (strstr(mode, "compat")) {
830 compatMake = TRUE;
831 forceJobs = FALSE;
833 #if USE_META
834 if (strstr(mode, "meta"))
835 meta_mode_init(mode);
836 #endif
839 free(mp);
843 * main --
844 * The main function, for obvious reasons. Initializes variables
845 * and a few modules, then parses the arguments give it in the
846 * environment and on the command line. Reads the system makefile
847 * followed by either Makefile, makefile or the file given by the
848 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
849 * flags it has received by then uses either the Make or the Compat
850 * module to create the initial list of targets.
852 * Results:
853 * If -q was given, exits -1 if anything was out-of-date. Else it exits
854 * 0.
856 * Side Effects:
857 * The program exits when done. Targets are created. etc. etc. etc.
860 main(int argc, char **argv)
862 Lst targs; /* target nodes to create -- passed to Make_Init */
863 Boolean outOfDate = FALSE; /* FALSE if all targets up to date */
864 struct stat sb, sa;
865 char *p1, *path;
866 char mdpath[MAXPATHLEN];
867 #ifdef FORCE_MACHINE
868 const char *machine = FORCE_MACHINE;
869 #else
870 const char *machine = getenv("MACHINE");
871 #endif
872 const char *machine_arch = getenv("MACHINE_ARCH");
873 char *syspath = getenv("MAKESYSPATH");
874 Lst sysMkPath; /* Path of sys.mk */
875 char *cp = NULL, *start;
876 /* avoid faults on read-only strings */
877 static char defsyspath[] = _PATH_DEFSYSPATH;
878 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
879 struct timeval rightnow; /* to initialize random seed */
880 struct utsname utsname;
882 /* default to writing debug to stderr */
883 debug_file = stderr;
885 #ifdef SIGINFO
886 (void)bmake_signal(SIGINFO, siginfo);
887 #endif
889 * Set the seed to produce a different random sequence
890 * on each program execution.
892 gettimeofday(&rightnow, NULL);
893 srandom(rightnow.tv_sec + rightnow.tv_usec);
895 if ((progname = strrchr(argv[0], '/')) != NULL)
896 progname++;
897 else
898 progname = argv[0];
899 #if defined(MAKE_NATIVE) || (defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE))
901 * get rid of resource limit on file descriptors
904 struct rlimit rl;
905 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
906 rl.rlim_cur != rl.rlim_max) {
907 rl.rlim_cur = rl.rlim_max;
908 (void)setrlimit(RLIMIT_NOFILE, &rl);
911 #endif
913 if (uname(&utsname) == -1) {
914 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
915 strerror(errno));
916 exit(2);
920 * Get the name of this type of MACHINE from utsname
921 * so we can share an executable for similar machines.
922 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
924 * Note that both MACHINE and MACHINE_ARCH are decided at
925 * run-time.
927 if (!machine) {
928 #ifdef MAKE_NATIVE
929 machine = utsname.machine;
930 #else
931 #ifdef MAKE_MACHINE
932 machine = MAKE_MACHINE;
933 #else
934 machine = "unknown";
935 #endif
936 #endif
939 if (!machine_arch) {
940 #if defined(MAKE_NATIVE) && defined(HAVE_SYSCTL) && defined(CTL_HW) && defined(HW_MACHINE_ARCH)
941 static char machine_arch_buf[sizeof(utsname.machine)];
942 int mib[2] = { CTL_HW, HW_MACHINE_ARCH };
943 size_t len = sizeof(machine_arch_buf);
945 if (sysctl(mib, __arraycount(mib), machine_arch_buf,
946 &len, NULL, 0) < 0) {
947 (void)fprintf(stderr, "%s: sysctl failed (%s).\n", progname,
948 strerror(errno));
949 exit(2);
952 machine_arch = machine_arch_buf;
953 #else
954 #ifndef MACHINE_ARCH
955 #ifdef MAKE_MACHINE_ARCH
956 machine_arch = MAKE_MACHINE_ARCH;
957 #else
958 machine_arch = "unknown";
959 #endif
960 #else
961 machine_arch = MACHINE_ARCH;
962 #endif
963 #endif
966 myPid = getpid(); /* remember this for vFork() */
969 * Just in case MAKEOBJDIR wants us to do something tricky.
971 Var_Init(); /* Initialize the lists of variables for
972 * parsing arguments */
973 Var_Set(".MAKE.OS", utsname.sysname, VAR_GLOBAL, 0);
974 Var_Set("MACHINE", machine, VAR_GLOBAL, 0);
975 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL, 0);
976 #ifdef MAKE_VERSION
977 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL, 0);
978 #endif
979 Var_Set(".newline", "\n", VAR_GLOBAL, 0); /* handy for :@ loops */
981 * This is the traditional preference for makefiles.
983 #ifndef MAKEFILE_PREFERENCE_LIST
984 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
985 #endif
986 Var_Set(MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST,
987 VAR_GLOBAL, 0);
988 Var_Set(MAKE_DEPENDFILE, ".depend", VAR_GLOBAL, 0);
990 create = Lst_Init(FALSE);
991 makefiles = Lst_Init(FALSE);
992 printVars = FALSE;
993 debugVflag = FALSE;
994 variables = Lst_Init(FALSE);
995 beSilent = FALSE; /* Print commands as executed */
996 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
997 noExecute = FALSE; /* Execute all commands */
998 noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
999 keepgoing = FALSE; /* Stop on error */
1000 allPrecious = FALSE; /* Remove targets when interrupted */
1001 deleteOnError = FALSE; /* Historical default behavior */
1002 queryFlag = FALSE; /* This is not just a check-run */
1003 noBuiltins = FALSE; /* Read the built-in rules */
1004 touchFlag = FALSE; /* Actually update targets */
1005 debug = 0; /* No debug verbosity, please. */
1006 jobsRunning = FALSE;
1008 maxJobs = DEFMAXLOCAL; /* Set default local max concurrency */
1009 maxJobTokens = maxJobs;
1010 compatMake = FALSE; /* No compat mode */
1011 ignorePWD = FALSE;
1014 * Initialize the parsing, directory and variable modules to prepare
1015 * for the reading of inclusion paths and variable settings on the
1016 * command line
1020 * Initialize various variables.
1021 * MAKE also gets this name, for compatibility
1022 * .MAKEFLAGS gets set to the empty string just in case.
1023 * MFLAGS also gets initialized empty, for compatibility.
1025 Parse_Init();
1026 if (argv[0][0] == '/' || strchr(argv[0], '/') == NULL) {
1028 * Leave alone if it is an absolute path, or if it does
1029 * not contain a '/' in which case we need to find it in
1030 * the path, like execvp(3) and the shells do.
1032 p1 = argv[0];
1033 } else {
1035 * A relative path, canonicalize it.
1037 p1 = cached_realpath(argv[0], mdpath);
1038 if (!p1 || *p1 != '/' || stat(p1, &sb) < 0) {
1039 p1 = argv[0]; /* realpath failed */
1042 Var_Set("MAKE", p1, VAR_GLOBAL, 0);
1043 Var_Set(".MAKE", p1, VAR_GLOBAL, 0);
1044 Var_Set(MAKEFLAGS, "", VAR_GLOBAL, 0);
1045 Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL, 0);
1046 Var_Set("MFLAGS", "", VAR_GLOBAL, 0);
1047 Var_Set(".ALLTARGETS", "", VAR_GLOBAL, 0);
1048 /* some makefiles need to know this */
1049 Var_Set(MAKE_LEVEL ".ENV", MAKE_LEVEL_ENV, VAR_CMD, 0);
1052 * Set some other useful macros
1055 char tmp[64], *ep;
1057 makelevel = ((ep = getenv(MAKE_LEVEL_ENV)) && *ep) ? atoi(ep) : 0;
1058 if (makelevel < 0)
1059 makelevel = 0;
1060 snprintf(tmp, sizeof(tmp), "%d", makelevel);
1061 Var_Set(MAKE_LEVEL, tmp, VAR_GLOBAL, 0);
1062 snprintf(tmp, sizeof(tmp), "%u", myPid);
1063 Var_Set(".MAKE.PID", tmp, VAR_GLOBAL, 0);
1064 snprintf(tmp, sizeof(tmp), "%u", getppid());
1065 Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL, 0);
1067 if (makelevel > 0) {
1068 char pn[1024];
1069 snprintf(pn, sizeof(pn), "%s[%d]", progname, makelevel);
1070 progname = bmake_strdup(pn);
1073 #ifdef USE_META
1074 meta_init();
1075 #endif
1076 Dir_Init(NULL); /* Dir_* safe to call from MainParseArgs */
1079 * First snag any flags out of the MAKE environment variable.
1080 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
1081 * in a different format).
1083 #ifdef POSIX
1084 p1 = explode(getenv("MAKEFLAGS"));
1085 Main_ParseArgLine(p1);
1086 free(p1);
1087 #else
1088 Main_ParseArgLine(getenv("MAKE"));
1089 #endif
1092 * Find where we are (now).
1093 * We take care of PWD for the automounter below...
1095 if (getcwd(curdir, MAXPATHLEN) == NULL) {
1096 (void)fprintf(stderr, "%s: getcwd: %s.\n",
1097 progname, strerror(errno));
1098 exit(2);
1101 MainParseArgs(argc, argv);
1103 if (enterFlag)
1104 printf("%s: Entering directory `%s'\n", progname, curdir);
1107 * Verify that cwd is sane.
1109 if (stat(curdir, &sa) == -1) {
1110 (void)fprintf(stderr, "%s: %s: %s.\n",
1111 progname, curdir, strerror(errno));
1112 exit(2);
1116 * All this code is so that we know where we are when we start up
1117 * on a different machine with pmake.
1118 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
1119 * since the value of curdir can vary depending on how we got
1120 * here. Ie sitting at a shell prompt (shell that provides $PWD)
1121 * or via subdir.mk in which case its likely a shell which does
1122 * not provide it.
1123 * So, to stop it breaking this case only, we ignore PWD if
1124 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
1126 #ifndef NO_PWD_OVERRIDE
1127 if (!ignorePWD) {
1128 char *pwd, *ptmp1 = NULL, *ptmp2 = NULL;
1130 if ((pwd = getenv("PWD")) != NULL &&
1131 Var_Value("MAKEOBJDIRPREFIX", VAR_CMD, &ptmp1) == NULL) {
1132 const char *makeobjdir = Var_Value("MAKEOBJDIR",
1133 VAR_CMD, &ptmp2);
1135 if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
1136 if (stat(pwd, &sb) == 0 &&
1137 sa.st_ino == sb.st_ino &&
1138 sa.st_dev == sb.st_dev)
1139 (void)strncpy(curdir, pwd, MAXPATHLEN);
1142 free(ptmp1);
1143 free(ptmp2);
1145 #endif
1146 Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0);
1149 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
1150 * MAKEOBJDIR is set in the environment, try only that value
1151 * and fall back to .CURDIR if it does not exist.
1153 * Otherwise, try _PATH_OBJDIR.MACHINE-MACHINE_ARCH, _PATH_OBJDIR.MACHINE,
1154 * and * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
1155 * of these paths exist, just use .CURDIR.
1157 Dir_Init(curdir);
1158 (void)Main_SetObjdir("%s", curdir);
1160 if (!Main_SetVarObjdir("MAKEOBJDIRPREFIX", curdir) &&
1161 !Main_SetVarObjdir("MAKEOBJDIR", "") &&
1162 !Main_SetObjdir("%s.%s-%s", _PATH_OBJDIR, machine, machine_arch) &&
1163 !Main_SetObjdir("%s.%s", _PATH_OBJDIR, machine) &&
1164 !Main_SetObjdir("%s", _PATH_OBJDIR))
1165 (void)Main_SetObjdir("%s%s", _PATH_OBJDIRPREFIX, curdir);
1168 * Initialize archive, target and suffix modules in preparation for
1169 * parsing the makefile(s)
1171 Arch_Init();
1172 Targ_Init();
1173 Suff_Init();
1174 Trace_Init(tracefile);
1176 DEFAULT = NULL;
1177 (void)time(&now);
1179 Trace_Log(MAKESTART, NULL);
1182 * Set up the .TARGETS variable to contain the list of targets to be
1183 * created. If none specified, make the variable empty -- the parser
1184 * will fill the thing in with the default or .MAIN target.
1186 if (!Lst_IsEmpty(create)) {
1187 LstNode ln;
1189 for (ln = Lst_First(create); ln != NULL;
1190 ln = Lst_Succ(ln)) {
1191 char *name = (char *)Lst_Datum(ln);
1193 Var_Append(".TARGETS", name, VAR_GLOBAL);
1195 } else
1196 Var_Set(".TARGETS", "", VAR_GLOBAL, 0);
1200 * If no user-supplied system path was given (through the -m option)
1201 * add the directories from the DEFSYSPATH (more than one may be given
1202 * as dir1:...:dirn) to the system include path.
1204 if (syspath == NULL || *syspath == '\0')
1205 syspath = defsyspath;
1206 else
1207 syspath = bmake_strdup(syspath);
1209 for (start = syspath; *start != '\0'; start = cp) {
1210 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1211 continue;
1212 if (*cp == ':') {
1213 *cp++ = '\0';
1215 /* look for magic parent directory search string */
1216 if (strncmp(".../", start, 4) != 0) {
1217 (void)Dir_AddDir(defIncPath, start);
1218 } else {
1219 if (Dir_FindHereOrAbove(curdir, start+4,
1220 found_path, sizeof(found_path))) {
1221 (void)Dir_AddDir(defIncPath, found_path);
1225 if (syspath != defsyspath)
1226 free(syspath);
1229 * Read in the built-in rules first, followed by the specified
1230 * makefile, if it was (makefile != NULL), or the default
1231 * makefile and Makefile, in that order, if it wasn't.
1233 if (!noBuiltins) {
1234 LstNode ln;
1236 sysMkPath = Lst_Init(FALSE);
1237 Dir_Expand(_PATH_DEFSYSMK,
1238 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
1239 sysMkPath);
1240 if (Lst_IsEmpty(sysMkPath))
1241 Fatal("%s: no system rules (%s).", progname,
1242 _PATH_DEFSYSMK);
1243 ln = Lst_Find(sysMkPath, NULL, ReadMakefile);
1244 if (ln == NULL)
1245 Fatal("%s: cannot open %s.", progname,
1246 (char *)Lst_Datum(ln));
1249 if (!Lst_IsEmpty(makefiles)) {
1250 LstNode ln;
1252 ln = Lst_Find(makefiles, NULL, ReadAllMakefiles);
1253 if (ln != NULL)
1254 Fatal("%s: cannot open %s.", progname,
1255 (char *)Lst_Datum(ln));
1256 } else {
1257 p1 = Var_Subst(NULL, "${" MAKEFILE_PREFERENCE "}",
1258 VAR_CMD, VARF_WANTRES);
1259 if (p1) {
1260 (void)str2Lst_Append(makefiles, p1, NULL);
1261 (void)Lst_Find(makefiles, NULL, ReadMakefile);
1262 free(p1);
1266 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1267 if (!noBuiltins || !printVars) {
1268 makeDependfile = Var_Subst(NULL, "${.MAKE.DEPENDFILE:T}",
1269 VAR_CMD, VARF_WANTRES);
1270 doing_depend = TRUE;
1271 (void)ReadMakefile(makeDependfile, NULL);
1272 doing_depend = FALSE;
1275 if (enterFlagObj)
1276 printf("%s: Entering directory `%s'\n", progname, objdir);
1278 MakeMode(NULL);
1280 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
1281 free(p1);
1283 if (!forceJobs && !compatMake &&
1284 Var_Exists(".MAKE.JOBS", VAR_GLOBAL)) {
1285 char *value;
1286 int n;
1288 value = Var_Subst(NULL, "${.MAKE.JOBS}", VAR_GLOBAL, VARF_WANTRES);
1289 n = strtol(value, NULL, 0);
1290 if (n < 1) {
1291 (void)fprintf(stderr, "%s: illegal value for .MAKE.JOBS -- must be positive integer!\n",
1292 progname);
1293 exit(1);
1295 if (n != maxJobs) {
1296 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
1297 Var_Append(MAKEFLAGS, value, VAR_GLOBAL);
1299 maxJobs = n;
1300 maxJobTokens = maxJobs;
1301 forceJobs = TRUE;
1302 free(value);
1306 * Be compatible if user did not specify -j and did not explicitly
1307 * turned compatibility on
1309 if (!compatMake && !forceJobs) {
1310 compatMake = TRUE;
1313 if (!compatMake)
1314 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1315 if (DEBUG(JOB))
1316 fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1317 jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
1319 if (!printVars)
1320 Main_ExportMAKEFLAGS(TRUE); /* initial export */
1323 * For compatibility, look at the directories in the VPATH variable
1324 * and add them to the search path, if the variable is defined. The
1325 * variable's value is in the same format as the PATH envariable, i.e.
1326 * <directory>:<directory>:<directory>...
1328 if (Var_Exists("VPATH", VAR_CMD)) {
1329 char *vpath, savec;
1331 * GCC stores string constants in read-only memory, but
1332 * Var_Subst will want to write this thing, so store it
1333 * in an array
1335 static char VPATH[] = "${VPATH}";
1337 vpath = Var_Subst(NULL, VPATH, VAR_CMD, VARF_WANTRES);
1338 path = vpath;
1339 do {
1340 /* skip to end of directory */
1341 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1342 continue;
1343 /* Save terminator character so know when to stop */
1344 savec = *cp;
1345 *cp = '\0';
1346 /* Add directory to search path */
1347 (void)Dir_AddDir(dirSearchPath, path);
1348 *cp = savec;
1349 path = cp + 1;
1350 } while (savec == ':');
1351 free(vpath);
1355 * Now that all search paths have been read for suffixes et al, it's
1356 * time to add the default search path to their lists...
1358 Suff_DoPaths();
1361 * Propagate attributes through :: dependency lists.
1363 Targ_Propagate();
1365 /* print the initial graph, if the user requested it */
1366 if (DEBUG(GRAPH1))
1367 Targ_PrintGraph(1);
1369 /* print the values of any variables requested by the user */
1370 if (printVars) {
1371 LstNode ln;
1372 Boolean expandVars;
1374 if (debugVflag)
1375 expandVars = FALSE;
1376 else
1377 expandVars = getBoolean(".MAKE.EXPAND_VARIABLES", FALSE);
1378 for (ln = Lst_First(variables); ln != NULL;
1379 ln = Lst_Succ(ln)) {
1380 char *var = (char *)Lst_Datum(ln);
1381 char *value;
1383 if (strchr(var, '$')) {
1384 value = p1 = Var_Subst(NULL, var, VAR_GLOBAL,
1385 VARF_WANTRES);
1386 } else if (expandVars) {
1387 char tmp[128];
1389 if (snprintf(tmp, sizeof(tmp), "${%s}", var) >= (int)(sizeof(tmp)))
1390 Fatal("%s: variable name too big: %s",
1391 progname, var);
1392 value = p1 = Var_Subst(NULL, tmp, VAR_GLOBAL,
1393 VARF_WANTRES);
1394 } else {
1395 value = Var_Value(var, VAR_GLOBAL, &p1);
1397 printf("%s\n", value ? value : "");
1398 free(p1);
1400 } else {
1402 * Have now read the entire graph and need to make a list of
1403 * targets to create. If none was given on the command line,
1404 * we consult the parsing module to find the main target(s)
1405 * to create.
1407 if (Lst_IsEmpty(create))
1408 targs = Parse_MainName();
1409 else
1410 targs = Targ_FindList(create, TARG_CREATE);
1412 if (!compatMake) {
1414 * Initialize job module before traversing the graph
1415 * now that any .BEGIN and .END targets have been read.
1416 * This is done only if the -q flag wasn't given
1417 * (to prevent the .BEGIN from being executed should
1418 * it exist).
1420 if (!queryFlag) {
1421 Job_Init();
1422 jobsRunning = TRUE;
1425 /* Traverse the graph, checking on all the targets */
1426 outOfDate = Make_Run(targs);
1427 } else {
1429 * Compat_Init will take care of creating all the
1430 * targets as well as initializing the module.
1432 Compat_Run(targs);
1436 #ifdef CLEANUP
1437 Lst_Destroy(targs, NULL);
1438 Lst_Destroy(variables, NULL);
1439 Lst_Destroy(makefiles, NULL);
1440 Lst_Destroy(create, (FreeProc *)free);
1441 #endif
1443 /* print the graph now it's been processed if the user requested it */
1444 if (DEBUG(GRAPH2))
1445 Targ_PrintGraph(2);
1447 Trace_Log(MAKEEND, 0);
1449 if (enterFlagObj)
1450 printf("%s: Leaving directory `%s'\n", progname, objdir);
1451 if (enterFlag)
1452 printf("%s: Leaving directory `%s'\n", progname, curdir);
1454 #ifdef USE_META
1455 meta_finish();
1456 #endif
1457 Suff_End();
1458 Targ_End();
1459 Arch_End();
1460 Var_End();
1461 Parse_End();
1462 Dir_End();
1463 Job_End();
1464 Trace_End();
1466 return outOfDate ? 1 : 0;
1470 * ReadMakefile --
1471 * Open and parse the given makefile.
1473 * Results:
1474 * 0 if ok. -1 if couldn't open file.
1476 * Side Effects:
1477 * lots
1479 static int
1480 ReadMakefile(const void *p, const void *q MAKE_ATTR_UNUSED)
1482 const char *fname = p; /* makefile to read */
1483 int fd;
1484 size_t len = MAXPATHLEN;
1485 char *name, *path = bmake_malloc(len);
1487 if (!strcmp(fname, "-")) {
1488 Parse_File(NULL /*stdin*/, -1);
1489 Var_Set("MAKEFILE", "", VAR_INTERNAL, 0);
1490 } else {
1491 /* if we've chdir'd, rebuild the path name */
1492 if (strcmp(curdir, objdir) && *fname != '/') {
1493 size_t plen = strlen(curdir) + strlen(fname) + 2;
1494 if (len < plen)
1495 path = bmake_realloc(path, len = 2 * plen);
1497 (void)snprintf(path, len, "%s/%s", curdir, fname);
1498 fd = open(path, O_RDONLY);
1499 if (fd != -1) {
1500 fname = path;
1501 goto found;
1504 /* If curdir failed, try objdir (ala .depend) */
1505 plen = strlen(objdir) + strlen(fname) + 2;
1506 if (len < plen)
1507 path = bmake_realloc(path, len = 2 * plen);
1508 (void)snprintf(path, len, "%s/%s", objdir, fname);
1509 fd = open(path, O_RDONLY);
1510 if (fd != -1) {
1511 fname = path;
1512 goto found;
1514 } else {
1515 fd = open(fname, O_RDONLY);
1516 if (fd != -1)
1517 goto found;
1519 /* look in -I and system include directories. */
1520 name = Dir_FindFile(fname, parseIncPath);
1521 if (!name)
1522 name = Dir_FindFile(fname,
1523 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1524 if (!name || (fd = open(name, O_RDONLY)) == -1) {
1525 free(name);
1526 free(path);
1527 return(-1);
1529 fname = name;
1531 * set the MAKEFILE variable desired by System V fans -- the
1532 * placement of the setting here means it gets set to the last
1533 * makefile specified, as it is set by SysV make.
1535 found:
1536 if (!doing_depend)
1537 Var_Set("MAKEFILE", fname, VAR_INTERNAL, 0);
1538 Parse_File(fname, fd);
1540 free(path);
1541 return(0);
1547 * Cmd_Exec --
1548 * Execute the command in cmd, and return the output of that command
1549 * in a string.
1551 * Results:
1552 * A string containing the output of the command, or the empty string
1553 * If errnum is not NULL, it contains the reason for the command failure
1555 * Side Effects:
1556 * The string must be freed by the caller.
1558 char *
1559 Cmd_Exec(const char *cmd, const char **errnum)
1561 const char *args[4]; /* Args for invoking the shell */
1562 int fds[2]; /* Pipe streams */
1563 int cpid; /* Child PID */
1564 int pid; /* PID from wait() */
1565 char *res; /* result */
1566 WAIT_T status; /* command exit status */
1567 Buffer buf; /* buffer to store the result */
1568 char *cp;
1569 int cc; /* bytes read, or -1 */
1570 int savederr; /* saved errno */
1573 *errnum = NULL;
1575 if (!shellName)
1576 Shell_Init();
1578 * Set up arguments for shell
1580 args[0] = shellName;
1581 args[1] = "-c";
1582 args[2] = cmd;
1583 args[3] = NULL;
1586 * Open a pipe for fetching its output
1588 if (pipe(fds) == -1) {
1589 *errnum = "Couldn't create pipe for \"%s\"";
1590 goto bad;
1594 * Fork
1596 switch (cpid = vFork()) {
1597 case 0:
1599 * Close input side of pipe
1601 (void)close(fds[0]);
1604 * Duplicate the output stream to the shell's output, then
1605 * shut the extra thing down. Note we don't fetch the error
1606 * stream...why not? Why?
1608 (void)dup2(fds[1], 1);
1609 (void)close(fds[1]);
1611 Var_ExportVars();
1613 (void)execv(shellPath, UNCONST(args));
1614 _exit(1);
1615 /*NOTREACHED*/
1617 case -1:
1618 *errnum = "Couldn't exec \"%s\"";
1619 goto bad;
1621 default:
1623 * No need for the writing half
1625 (void)close(fds[1]);
1627 savederr = 0;
1628 Buf_Init(&buf, 0);
1630 do {
1631 char result[BUFSIZ];
1632 cc = read(fds[0], result, sizeof(result));
1633 if (cc > 0)
1634 Buf_AddBytes(&buf, cc, result);
1636 while (cc > 0 || (cc == -1 && errno == EINTR));
1637 if (cc == -1)
1638 savederr = errno;
1641 * Close the input side of the pipe.
1643 (void)close(fds[0]);
1646 * Wait for the process to exit.
1648 while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) {
1649 JobReapChild(pid, status, FALSE);
1650 continue;
1652 cc = Buf_Size(&buf);
1653 res = Buf_Destroy(&buf, FALSE);
1655 if (savederr != 0)
1656 *errnum = "Couldn't read shell's output for \"%s\"";
1658 if (WIFSIGNALED(status))
1659 *errnum = "\"%s\" exited on a signal";
1660 else if (WEXITSTATUS(status) != 0)
1661 *errnum = "\"%s\" returned non-zero status";
1664 * Null-terminate the result, convert newlines to spaces and
1665 * install it in the variable.
1667 res[cc] = '\0';
1668 cp = &res[cc];
1670 if (cc > 0 && *--cp == '\n') {
1672 * A final newline is just stripped
1674 *cp-- = '\0';
1676 while (cp >= res) {
1677 if (*cp == '\n') {
1678 *cp = ' ';
1680 cp--;
1682 break;
1684 return res;
1685 bad:
1686 res = bmake_malloc(1);
1687 *res = '\0';
1688 return res;
1692 * Error --
1693 * Print an error message given its format.
1695 * Results:
1696 * None.
1698 * Side Effects:
1699 * The message is printed.
1701 /* VARARGS */
1702 void
1703 Error(const char *fmt, ...)
1705 va_list ap;
1706 FILE *err_file;
1708 err_file = debug_file;
1709 if (err_file == stdout)
1710 err_file = stderr;
1711 (void)fflush(stdout);
1712 for (;;) {
1713 va_start(ap, fmt);
1714 fprintf(err_file, "%s: ", progname);
1715 (void)vfprintf(err_file, fmt, ap);
1716 va_end(ap);
1717 (void)fprintf(err_file, "\n");
1718 (void)fflush(err_file);
1719 if (err_file == stderr)
1720 break;
1721 err_file = stderr;
1726 * Fatal --
1727 * Produce a Fatal error message. If jobs are running, waits for them
1728 * to finish.
1730 * Results:
1731 * None
1733 * Side Effects:
1734 * The program exits
1736 /* VARARGS */
1737 void
1738 Fatal(const char *fmt, ...)
1740 va_list ap;
1742 va_start(ap, fmt);
1743 if (jobsRunning)
1744 Job_Wait();
1746 (void)fflush(stdout);
1747 (void)vfprintf(stderr, fmt, ap);
1748 va_end(ap);
1749 (void)fprintf(stderr, "\n");
1750 (void)fflush(stderr);
1752 PrintOnError(NULL, NULL);
1754 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1755 Targ_PrintGraph(2);
1756 Trace_Log(MAKEERROR, 0);
1757 exit(2); /* Not 1 so -q can distinguish error */
1761 * Punt --
1762 * Major exception once jobs are being created. Kills all jobs, prints
1763 * a message and exits.
1765 * Results:
1766 * None
1768 * Side Effects:
1769 * All children are killed indiscriminately and the program Lib_Exits
1771 /* VARARGS */
1772 void
1773 Punt(const char *fmt, ...)
1775 va_list ap;
1777 va_start(ap, fmt);
1778 (void)fflush(stdout);
1779 (void)fprintf(stderr, "%s: ", progname);
1780 (void)vfprintf(stderr, fmt, ap);
1781 va_end(ap);
1782 (void)fprintf(stderr, "\n");
1783 (void)fflush(stderr);
1785 PrintOnError(NULL, NULL);
1787 DieHorribly();
1791 * DieHorribly --
1792 * Exit without giving a message.
1794 * Results:
1795 * None
1797 * Side Effects:
1798 * A big one...
1800 void
1801 DieHorribly(void)
1803 if (jobsRunning)
1804 Job_AbortAll();
1805 if (DEBUG(GRAPH2))
1806 Targ_PrintGraph(2);
1807 Trace_Log(MAKEERROR, 0);
1808 exit(2); /* Not 1, so -q can distinguish error */
1812 * Finish --
1813 * Called when aborting due to errors in child shell to signal
1814 * abnormal exit.
1816 * Results:
1817 * None
1819 * Side Effects:
1820 * The program exits
1822 void
1823 Finish(int errors)
1824 /* number of errors encountered in Make_Make */
1826 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1830 * eunlink --
1831 * Remove a file carefully, avoiding directories.
1834 eunlink(const char *file)
1836 struct stat st;
1838 if (lstat(file, &st) == -1)
1839 return -1;
1841 if (S_ISDIR(st.st_mode)) {
1842 errno = EISDIR;
1843 return -1;
1845 return unlink(file);
1849 * execError --
1850 * Print why exec failed, avoiding stdio.
1852 void
1853 execError(const char *af, const char *av)
1855 #ifdef USE_IOVEC
1856 int i = 0;
1857 struct iovec iov[8];
1858 #define IOADD(s) \
1859 (void)(iov[i].iov_base = UNCONST(s), \
1860 iov[i].iov_len = strlen(iov[i].iov_base), \
1861 i++)
1862 #else
1863 #define IOADD(s) (void)write(2, s, strlen(s))
1864 #endif
1866 IOADD(progname);
1867 IOADD(": ");
1868 IOADD(af);
1869 IOADD("(");
1870 IOADD(av);
1871 IOADD(") failed (");
1872 IOADD(strerror(errno));
1873 IOADD(")\n");
1875 #ifdef USE_IOVEC
1876 while (writev(2, iov, 8) == -1 && errno == EAGAIN)
1877 continue;
1878 #endif
1882 * usage --
1883 * exit with usage message
1885 static void
1886 usage(void)
1888 char *p;
1889 if ((p = strchr(progname, '[')) != NULL)
1890 *p = '\0';
1892 (void)fprintf(stderr,
1893 "usage: %s [-BeikNnqrstWwX] \n\
1894 [-C directory] [-D variable] [-d flags] [-f makefile]\n\
1895 [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1896 [-V variable] [variable=value] [target ...]\n", progname);
1897 exit(2);
1902 * realpath(3) can get expensive, cache results...
1904 char *
1905 cached_realpath(const char *pathname, char *resolved)
1907 static GNode *cache;
1908 char *rp, *cp;
1910 if (!pathname || !pathname[0])
1911 return NULL;
1913 if (!cache) {
1914 cache = Targ_NewGN("Realpath");
1915 #ifndef DEBUG_REALPATH_CACHE
1916 cache->flags = INTERNAL;
1917 #endif
1920 if ((rp = Var_Value(pathname, cache, &cp)) != NULL) {
1921 /* a hit */
1922 strlcpy(resolved, rp, MAXPATHLEN);
1923 } else if ((rp = realpath(pathname, resolved)) != NULL) {
1924 Var_Set(pathname, rp, cache, 0);
1926 free(cp);
1927 return rp ? resolved : NULL;
1931 PrintAddr(void *a, void *b)
1933 printf("%lx ", (unsigned long) a);
1934 return b ? 0 : 0;
1938 static int
1939 addErrorCMD(void *cmdp, void *gnp MAKE_ATTR_UNUSED)
1941 if (cmdp == NULL)
1942 return 1; /* stop */
1943 Var_Append(".ERROR_CMD", cmdp, VAR_GLOBAL);
1944 return 0;
1947 void
1948 PrintOnError(GNode *gn, const char *s)
1950 static GNode *en = NULL;
1951 char tmp[64];
1952 char *cp;
1954 if (s)
1955 printf("%s", s);
1957 printf("\n%s: stopped in %s\n", progname, curdir);
1959 if (en)
1960 return; /* we've been here! */
1961 if (gn) {
1963 * We can print this even if there is no .ERROR target.
1965 Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL, 0);
1966 Var_Delete(".ERROR_CMD", VAR_GLOBAL);
1967 Lst_ForEach(gn->commands, addErrorCMD, gn);
1969 strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1970 sizeof(tmp) - 1);
1971 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, VARF_WANTRES);
1972 if (cp) {
1973 if (*cp)
1974 printf("%s", cp);
1975 free(cp);
1977 fflush(stdout);
1980 * Finally, see if there is a .ERROR target, and run it if so.
1982 en = Targ_FindNode(".ERROR", TARG_NOCREATE);
1983 if (en) {
1984 en->type |= OP_SPECIAL;
1985 Compat_Make(en, en);
1989 void
1990 Main_ExportMAKEFLAGS(Boolean first)
1992 static int once = 1;
1993 char tmp[64];
1994 char *s;
1996 if (once != first)
1997 return;
1998 once = 0;
2000 strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
2001 sizeof(tmp));
2002 s = Var_Subst(NULL, tmp, VAR_CMD, VARF_WANTRES);
2003 if (s && *s) {
2004 #ifdef POSIX
2005 setenv("MAKEFLAGS", s, 1);
2006 #else
2007 setenv("MAKE", s, 1);
2008 #endif
2012 char *
2013 getTmpdir(void)
2015 static char *tmpdir = NULL;
2017 if (!tmpdir) {
2018 struct stat st;
2021 * Honor $TMPDIR but only if it is valid.
2022 * Ensure it ends with /.
2024 tmpdir = Var_Subst(NULL, "${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL,
2025 VARF_WANTRES);
2026 if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
2027 free(tmpdir);
2028 tmpdir = bmake_strdup(_PATH_TMP);
2031 return tmpdir;
2035 * Create and open a temp file using "pattern".
2036 * If "fnamep" is provided set it to a copy of the filename created.
2037 * Otherwise unlink the file once open.
2040 mkTempFile(const char *pattern, char **fnamep)
2042 static char *tmpdir = NULL;
2043 char tfile[MAXPATHLEN];
2044 int fd;
2046 if (!pattern)
2047 pattern = TMPPAT;
2048 if (!tmpdir)
2049 tmpdir = getTmpdir();
2050 if (pattern[0] == '/') {
2051 snprintf(tfile, sizeof(tfile), "%s", pattern);
2052 } else {
2053 snprintf(tfile, sizeof(tfile), "%s%s", tmpdir, pattern);
2055 if ((fd = mkstemp(tfile)) < 0)
2056 Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
2057 if (fnamep) {
2058 *fnamep = bmake_strdup(tfile);
2059 } else {
2060 unlink(tfile); /* we just want the descriptor */
2062 return fd;
2066 * Convert a string representation of a boolean.
2067 * Anything that looks like "No", "False", "Off", "0" etc,
2068 * is FALSE, otherwise TRUE.
2070 Boolean
2071 s2Boolean(const char *s, Boolean bf)
2073 if (s) {
2074 switch(*s) {
2075 case '\0': /* not set - the default wins */
2076 break;
2077 case '0':
2078 case 'F':
2079 case 'f':
2080 case 'N':
2081 case 'n':
2082 bf = FALSE;
2083 break;
2084 case 'O':
2085 case 'o':
2086 switch (s[1]) {
2087 case 'F':
2088 case 'f':
2089 bf = FALSE;
2090 break;
2091 default:
2092 bf = TRUE;
2093 break;
2095 break;
2096 default:
2097 bf = TRUE;
2098 break;
2101 return (bf);
2105 * Return a Boolean based on setting of a knob.
2107 * If the knob is not set, the supplied default is the return value.
2108 * If set, anything that looks or smells like "No", "False", "Off", "0" etc,
2109 * is FALSE, otherwise TRUE.
2111 Boolean
2112 getBoolean(const char *name, Boolean bf)
2114 char tmp[64];
2115 char *cp;
2117 if (snprintf(tmp, sizeof(tmp), "${%s:U:tl}", name) < (int)(sizeof(tmp))) {
2118 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, VARF_WANTRES);
2120 if (cp) {
2121 bf = s2Boolean(cp, bf);
2122 free(cp);
2125 return (bf);