1 /* $NetBSD: main.c,v 1.279 2020/07/03 08:13:23 rillig Exp $ */
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
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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
36 * Copyright (c) 1989 by Berkeley Softworks
37 * All rights reserved.
39 * This code is derived from software contributed to Berkeley by
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
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
72 static char rcsid[] = "$NetBSD: main.c,v 1.279 2020/07/03 08:13:23 rillig Exp $";
74 #include <sys/cdefs.h>
76 __COPYRIGHT("@(#) Copyright (c) 1988, 1989, 1990, 1993\
77 The Regents of the University of California. All rights reserved.");
82 static char sccsid[] = "@(#)main.c 8.3 (Berkeley) 3/19/94";
84 __RCSID("$NetBSD: main.c,v 1.279 2020/07/03 08:13:23 rillig Exp $");
91 * The main file for this entire program. Exit routines etc
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
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
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
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>
124 #include <sys/utsname.h>
139 #include "pathnames.h"
147 #define DEFMAXLOCAL DEFMAXJOBS
148 #endif /* DEFMAXLOCAL */
151 # define __arraycount(__x) (sizeof(__x) / sizeof(__x[0]))
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 int printVars; /* -[vV] argument */
163 #define COMPAT_VARS 1
164 #define EXPAND_VARS 2
165 static Lst variables; /* list of variables to print */
166 int maxJobs; /* -j argument */
167 static int maxJobTokens; /* -j argument */
168 Boolean compatMake; /* -B argument */
169 int debug; /* -d argument */
170 Boolean debugVflag; /* -dV */
171 Boolean noExecute; /* -n flag */
172 Boolean noRecursiveExecute; /* -N flag */
173 Boolean keepgoing; /* -k flag */
174 Boolean queryFlag; /* -q flag */
175 Boolean touchFlag; /* -t flag */
176 Boolean enterFlag; /* -w flag */
177 Boolean enterFlagObj; /* -w and objdir != srcdir */
178 Boolean ignoreErrors; /* -i flag */
179 Boolean beSilent; /* -s flag */
180 Boolean oldVars; /* variable substitution style */
181 Boolean checkEnvFirst; /* -e flag */
182 Boolean parseWarnFatal; /* -W flag */
183 Boolean jobServer; /* -J flag */
184 static int jp_0 = -1, jp_1 = -1; /* ends of parent job pipe */
185 Boolean varNoExportEnv; /* -X flag */
186 Boolean doing_depend; /* Set while reading .depend */
187 static Boolean jobsRunning; /* TRUE if the jobs might be running */
188 static const char * tracefile;
189 static void MainParseArgs(int, char **);
190 static int ReadMakefile(const void *, const void *);
191 static void usage(void) MAKE_ATTR_DEAD;
192 static void purge_cached_realpaths(void);
194 static Boolean ignorePWD; /* if we use -C, PWD is meaningless */
195 static char objdir[MAXPATHLEN + 1]; /* where we chdir'ed to */
196 char curdir[MAXPATHLEN + 1]; /* Startup directory */
197 char *progname; /* the program name */
198 char *makeDependfile;
204 Boolean forceJobs = FALSE;
207 * On some systems MACHINE is defined as something other than
212 # define MACHINE FORCE_MACHINE
215 extern Lst parseIncPath;
218 * For compatibility with the POSIX version of MAKEFLAGS that includes
219 * all the options with out -, convert flags to -f -l -a -g -s.
222 explode(const char *flags)
231 for (f = flags; *f; f++)
232 if (!isalpha((unsigned char)*f))
236 return bmake_strdup(flags);
239 st = nf = bmake_malloc(len * 3 + 1);
250 parse_debug_options(const char *argvalue)
257 for (modules = argvalue; *modules; ++modules) {
275 debug |= DEBUG_ERROR;
281 if (modules[1] == '1') {
282 debug |= DEBUG_GRAPH1;
285 else if (modules[1] == '2') {
286 debug |= DEBUG_GRAPH2;
289 else if (modules[1] == '3') {
290 debug |= DEBUG_GRAPH3;
307 debug |= DEBUG_SCRIPT;
310 debug |= DEBUG_PARSE;
325 debug |= DEBUG_SHELL;
328 if (debug_file != stdout && debug_file != stderr)
330 if (*++modules == '+') {
335 if (strcmp(modules, "stdout") == 0) {
339 if (strcmp(modules, "stderr") == 0) {
343 len = strlen(modules);
344 fname = bmake_malloc(len + 20);
345 memcpy(fname, modules, len + 1);
346 /* Let the filename be modified by the pid */
347 if (strcmp(fname + len - 3, ".%d") == 0)
348 snprintf(fname + len - 2, 20, "%d", getpid());
349 debug_file = fopen(fname, mode);
351 fprintf(stderr, "Cannot open debug file %s\n",
358 (void)fprintf(stderr,
359 "%s: illegal argument to d option -- %c\n",
366 * Make the debug_file unbuffered, and make
367 * stdout line buffered (unless debugfile == stdout).
369 setvbuf(debug_file, NULL, _IONBF, 0);
370 if (debug_file != stdout) {
371 setvbuf(stdout, NULL, _IOLBF, 0);
376 * does path contain any relative components
379 is_relpath(const char *path)
387 cp = strstr(cp, "/.");
391 if (cp[0] == '/' || cp[0] == '\0')
393 else if (cp[0] == '.') {
394 if (cp[1] == '/' || cp[1] == '\0')
403 * Parse a given argument vector. Called from main() and from
404 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
406 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
412 * Various global and local flags will be set depending on the flags
416 MainParseArgs(int argc, char **argv)
422 const char *getopt_def;
425 Boolean inOption, dashDash = FALSE;
426 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
428 #define OPTFLAGS "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrstv:w"
429 /* Can't actually use getopt(3) because rescanning is not portable */
431 getopt_def = OPTFLAGS;
449 if (c != '-' || dashDash)
454 /* '-' found at some earlier point */
455 getopt_spec = strchr(getopt_def, c);
456 if(c != '\0' && getopt_spec != NULL && getopt_spec[1] == ':') {
457 /* -<something> found, and <something> should have an arg */
461 if(*argvalue == '\0') {
477 Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
478 Var_Set(MAKE_MODE, "compat", VAR_GLOBAL);
481 if (chdir(argvalue) == -1) {
482 (void)fprintf(stderr,
483 "%s: chdir %s: %s\n",
488 if (getcwd(curdir, MAXPATHLEN) == NULL) {
489 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
492 if (!is_relpath(argvalue) &&
493 stat(argvalue, &sa) != -1 &&
494 stat(curdir, &sb) != -1 &&
495 sa.st_ino == sb.st_ino &&
496 sa.st_dev == sb.st_dev)
497 strncpy(curdir, argvalue, MAXPATHLEN);
501 if (argvalue == NULL || argvalue[0] == 0) goto noarg;
502 Var_Set(argvalue, "1", VAR_GLOBAL);
503 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
504 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
507 if (argvalue == NULL) goto noarg;
508 Parse_AddIncludeDir(argvalue);
509 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
510 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
513 if (argvalue == NULL) goto noarg;
514 if (sscanf(argvalue, "%d,%d", &jp_0, &jp_1) != 2) {
515 (void)fprintf(stderr,
516 "%s: internal error -- J option malformed (%s)\n",
520 if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
521 (fcntl(jp_1, F_GETFD, 0) < 0)) {
523 (void)fprintf(stderr,
524 "%s: ###### warning -- J descriptors were closed!\n",
532 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
533 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
539 noRecursiveExecute = TRUE;
540 Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
544 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
547 if (argvalue == NULL) goto noarg;
548 tracefile = bmake_strdup(argvalue);
549 Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
550 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
554 if (argvalue == NULL) goto noarg;
555 printVars = c == 'v' ? EXPAND_VARS : COMPAT_VARS;
556 (void)Lst_AtEnd(variables, argvalue);
557 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
558 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
561 parseWarnFatal = TRUE;
564 varNoExportEnv = TRUE;
565 Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
568 if (argvalue == NULL) goto noarg;
569 /* If '-d-opts' don't pass to children */
570 if (argvalue[0] == '-')
573 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
574 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
576 parse_debug_options(argvalue);
579 checkEnvFirst = TRUE;
580 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
583 if (argvalue == NULL) goto noarg;
584 (void)Lst_AtEnd(makefiles, argvalue);
588 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
591 if (argvalue == NULL) goto noarg;
593 maxJobs = strtol(argvalue, &p, 0);
594 if (*p != '\0' || maxJobs < 1) {
595 (void)fprintf(stderr, "%s: illegal argument to -j -- must be positive integer!\n",
599 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
600 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
601 Var_Set(".MAKE.JOBS", argvalue, VAR_GLOBAL);
602 maxJobTokens = maxJobs;
606 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
609 if (argvalue == NULL) goto noarg;
610 /* look for magic parent directory search string */
611 if (strncmp(".../", argvalue, 4) == 0) {
612 if (!Dir_FindHereOrAbove(curdir, argvalue+4,
613 found_path, sizeof(found_path)))
614 break; /* nothing doing */
615 (void)Dir_AddDir(sysIncPath, found_path);
617 (void)Dir_AddDir(sysIncPath, argvalue);
619 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
620 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
624 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
628 /* Kind of nonsensical, wot? */
629 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
633 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
637 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
641 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
645 Var_Append(MAKEFLAGS, "-w", VAR_GLOBAL);
653 fprintf(stderr, "getopt(%s) -> %d (%c)\n",
665 * See if the rest of the arguments are variable assignments and
666 * perform them if so. Else take them to be targets and stuff them
667 * on the end of the "create" list.
669 for (; argc > 1; ++argv, --argc)
670 if (Parse_IsVar(argv[1])) {
671 Parse_DoVar(argv[1], VAR_CMD);
674 Punt("illegal (null) argument.");
675 if (*argv[1] == '-' && !dashDash)
677 (void)Lst_AtEnd(create, bmake_strdup(argv[1]));
682 (void)fprintf(stderr, "%s: option requires an argument -- %c\n",
688 * Main_ParseArgLine --
689 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
690 * is encountered and by main() when reading the .MAKEFLAGS envariable.
691 * Takes a line of arguments and breaks it into its
692 * component words and passes those words and the number of them to the
693 * MainParseArgs function.
694 * The line should have all its leading whitespace removed.
697 * line Line to fracture
703 * Only those that come from the various arguments.
706 Main_ParseArgLine(const char *line)
708 char **argv; /* Manufactured argument vector */
709 int argc; /* Number of arguments in argv */
710 char *args; /* Space used by the args */
712 char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
717 for (; *line == ' '; ++line)
725 * $MAKE may simply be naming the make(1) binary
729 if (!(cp = strrchr(line, '/')))
731 if ((cp = strstr(cp, "make")) &&
732 strcmp(cp, "make") == 0)
736 buf = bmake_malloc(len = strlen(line) + strlen(argv0) + 2);
737 (void)snprintf(buf, len, "%s %s", argv0, line);
740 argv = brk_string(buf, &argc, TRUE, &args);
742 Error("Unterminated quoted string [%s]", buf);
747 MainParseArgs(argc, argv);
754 Main_SetObjdir(const char *fmt, ...)
758 char buf[MAXPATHLEN + 1];
759 char buf2[MAXPATHLEN + 1];
764 vsnprintf(path = buf, MAXPATHLEN, fmt, ap);
767 if (path[0] != '/') {
768 snprintf(buf2, MAXPATHLEN, "%s/%s", curdir, path);
772 /* look for the directory and try to chdir there */
773 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
775 (void)fprintf(stderr, "make warning: %s: %s.\n",
776 path, strerror(errno));
778 strncpy(objdir, path, MAXPATHLEN);
779 Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
780 setenv("PWD", objdir, 1);
782 purge_cached_realpaths();
784 if (enterFlag && strcmp(objdir, curdir) != 0)
793 Main_SetVarObjdir(const char *var, const char *suffix)
795 char *p, *path, *xpath;
797 if ((path = Var_Value(var, VAR_CMD, &p)) == NULL ||
801 /* expand variable substitutions */
802 if (strchr(path, '$') != 0)
803 xpath = Var_Subst(NULL, path, VAR_GLOBAL, VARF_WANTRES);
807 (void)Main_SetObjdir("%s%s", xpath, suffix);
816 * ReadAllMakefiles --
817 * wrapper around ReadMakefile() to read all.
820 * TRUE if ok, FALSE on error
823 ReadAllMakefiles(const void *p, const void *q)
825 return ReadMakefile(p, q) == 0;
829 str2Lst_Append(Lst lp, char *str, const char *sep)
837 for (n = 0, cp = strtok(str, sep); cp; cp = strtok(NULL, sep)) {
838 (void)Lst_AtEnd(lp, cp);
847 siginfo(int signo MAKE_ATTR_UNUSED)
849 char dir[MAXPATHLEN];
850 char str[2 * MAXPATHLEN];
852 if (getcwd(dir, sizeof(dir)) == NULL)
854 len = snprintf(str, sizeof(str), "%s: Working in: %s\n", progname, dir);
856 (void)write(STDERR_FILENO, str, (size_t)len);
861 * Allow makefiles some control over the mode we run in.
864 MakeMode(const char *mode)
869 mode = mp = Var_Subst(NULL, "${" MAKE_MODE ":tl}",
870 VAR_GLOBAL, VARF_WANTRES);
873 if (strstr(mode, "compat")) {
878 if (strstr(mode, "meta"))
879 meta_mode_init(mode);
892 if (printVars == EXPAND_VARS)
897 expandVars = getBoolean(".MAKE.EXPAND_VARIABLES", FALSE);
899 for (ln = Lst_First(variables); ln != NULL;
901 char *var = (char *)Lst_Datum(ln);
905 if (strchr(var, '$')) {
906 value = p1 = Var_Subst(NULL, var, VAR_GLOBAL,
908 } else if (expandVars) {
910 int len = snprintf(tmp, sizeof(tmp), "${%s}", var);
912 if (len >= (int)sizeof(tmp))
913 Fatal("%s: variable name too big: %s",
915 value = p1 = Var_Subst(NULL, tmp, VAR_GLOBAL,
918 value = Var_Value(var, VAR_GLOBAL, &p1);
920 printf("%s\n", value ? value : "");
928 Lst targs; /* target nodes to create -- passed to Make_Init */
929 Boolean outOfDate; /* FALSE if all targets up to date */
932 * Have now read the entire graph and need to make a list of
933 * targets to create. If none was given on the command line,
934 * we consult the parsing module to find the main target(s)
937 if (Lst_IsEmpty(create))
938 targs = Parse_MainName();
940 targs = Targ_FindList(create, TARG_CREATE);
944 * Initialize job module before traversing the graph
945 * now that any .BEGIN and .END targets have been read.
946 * This is done only if the -q flag wasn't given
947 * (to prevent the .BEGIN from being executed should
955 /* Traverse the graph, checking on all the targets */
956 outOfDate = Make_Run(targs);
959 * Compat_Init will take care of creating all the
960 * targets as well as initializing the module.
965 Lst_Destroy(targs, NULL);
971 * The main function, for obvious reasons. Initializes variables
972 * and a few modules, then parses the arguments give it in the
973 * environment and on the command line. Reads the system makefile
974 * followed by either Makefile, makefile or the file given by the
975 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
976 * flags it has received by then uses either the Make or the Compat
977 * module to create the initial list of targets.
980 * If -q was given, exits -1 if anything was out-of-date. Else it exits
984 * The program exits when done. Targets are created. etc. etc. etc.
987 main(int argc, char **argv)
989 Boolean outOfDate; /* FALSE if all targets up to date */
992 char mdpath[MAXPATHLEN];
994 const char *machine = FORCE_MACHINE;
996 const char *machine = getenv("MACHINE");
998 const char *machine_arch = getenv("MACHINE_ARCH");
999 char *syspath = getenv("MAKESYSPATH");
1000 Lst sysMkPath; /* Path of sys.mk */
1001 char *cp = NULL, *start;
1002 /* avoid faults on read-only strings */
1003 static char defsyspath[] = _PATH_DEFSYSPATH;
1004 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
1005 struct timeval rightnow; /* to initialize random seed */
1006 struct utsname utsname;
1008 /* default to writing debug to stderr */
1009 debug_file = stderr;
1012 (void)bmake_signal(SIGINFO, siginfo);
1015 * Set the seed to produce a different random sequence
1016 * on each program execution.
1018 gettimeofday(&rightnow, NULL);
1019 srandom(rightnow.tv_sec + rightnow.tv_usec);
1021 if ((progname = strrchr(argv[0], '/')) != NULL)
1025 #if defined(MAKE_NATIVE) || (defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE))
1027 * get rid of resource limit on file descriptors
1031 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
1032 rl.rlim_cur != rl.rlim_max) {
1033 rl.rlim_cur = rl.rlim_max;
1034 (void)setrlimit(RLIMIT_NOFILE, &rl);
1039 if (uname(&utsname) == -1) {
1040 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
1046 * Get the name of this type of MACHINE from utsname
1047 * so we can share an executable for similar machines.
1048 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
1050 * Note that both MACHINE and MACHINE_ARCH are decided at
1055 machine = utsname.machine;
1058 machine = MAKE_MACHINE;
1060 machine = "unknown";
1065 if (!machine_arch) {
1066 #if defined(MAKE_NATIVE) && defined(HAVE_SYSCTL) && defined(CTL_HW) && defined(HW_MACHINE_ARCH)
1067 static char machine_arch_buf[sizeof(utsname.machine)];
1068 int mib[2] = { CTL_HW, HW_MACHINE_ARCH };
1069 size_t len = sizeof(machine_arch_buf);
1071 if (sysctl(mib, __arraycount(mib), machine_arch_buf,
1072 &len, NULL, 0) < 0) {
1073 (void)fprintf(stderr, "%s: sysctl failed (%s).\n", progname,
1078 machine_arch = machine_arch_buf;
1080 #ifndef MACHINE_ARCH
1081 #ifdef MAKE_MACHINE_ARCH
1082 machine_arch = MAKE_MACHINE_ARCH;
1084 machine_arch = "unknown";
1087 machine_arch = MACHINE_ARCH;
1092 myPid = getpid(); /* remember this for vFork() */
1095 * Just in case MAKEOBJDIR wants us to do something tricky.
1097 Var_Init(); /* Initialize the lists of variables for
1098 * parsing arguments */
1099 Var_Set(".MAKE.OS", utsname.sysname, VAR_GLOBAL);
1100 Var_Set("MACHINE", machine, VAR_GLOBAL);
1101 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
1103 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
1105 Var_Set(".newline", "\n", VAR_GLOBAL); /* handy for :@ loops */
1107 * This is the traditional preference for makefiles.
1109 #ifndef MAKEFILE_PREFERENCE_LIST
1110 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
1112 Var_Set(MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST,
1114 Var_Set(MAKE_DEPENDFILE, ".depend", VAR_GLOBAL);
1116 create = Lst_Init(FALSE);
1117 makefiles = Lst_Init(FALSE);
1120 variables = Lst_Init(FALSE);
1121 beSilent = FALSE; /* Print commands as executed */
1122 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
1123 noExecute = FALSE; /* Execute all commands */
1124 noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
1125 keepgoing = FALSE; /* Stop on error */
1126 allPrecious = FALSE; /* Remove targets when interrupted */
1127 deleteOnError = FALSE; /* Historical default behavior */
1128 queryFlag = FALSE; /* This is not just a check-run */
1129 noBuiltins = FALSE; /* Read the built-in rules */
1130 touchFlag = FALSE; /* Actually update targets */
1131 debug = 0; /* No debug verbosity, please. */
1132 jobsRunning = FALSE;
1134 maxJobs = DEFMAXLOCAL; /* Set default local max concurrency */
1135 maxJobTokens = maxJobs;
1136 compatMake = FALSE; /* No compat mode */
1140 * Initialize the parsing, directory and variable modules to prepare
1141 * for the reading of inclusion paths and variable settings on the
1146 * Initialize various variables.
1147 * MAKE also gets this name, for compatibility
1148 * .MAKEFLAGS gets set to the empty string just in case.
1149 * MFLAGS also gets initialized empty, for compatibility.
1152 if (argv[0][0] == '/' || strchr(argv[0], '/') == NULL) {
1154 * Leave alone if it is an absolute path, or if it does
1155 * not contain a '/' in which case we need to find it in
1156 * the path, like execvp(3) and the shells do.
1161 * A relative path, canonicalize it.
1163 p1 = cached_realpath(argv[0], mdpath);
1164 if (!p1 || *p1 != '/' || stat(p1, &sb) < 0) {
1165 p1 = argv[0]; /* realpath failed */
1168 Var_Set("MAKE", p1, VAR_GLOBAL);
1169 Var_Set(".MAKE", p1, VAR_GLOBAL);
1170 Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
1171 Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL);
1172 Var_Set("MFLAGS", "", VAR_GLOBAL);
1173 Var_Set(".ALLTARGETS", "", VAR_GLOBAL);
1174 /* some makefiles need to know this */
1175 Var_Set(MAKE_LEVEL ".ENV", MAKE_LEVEL_ENV, VAR_CMD);
1178 * Set some other useful macros
1183 makelevel = ((ep = getenv(MAKE_LEVEL_ENV)) && *ep) ? atoi(ep) : 0;
1186 snprintf(tmp, sizeof(tmp), "%d", makelevel);
1187 Var_Set(MAKE_LEVEL, tmp, VAR_GLOBAL);
1188 snprintf(tmp, sizeof(tmp), "%u", myPid);
1189 Var_Set(".MAKE.PID", tmp, VAR_GLOBAL);
1190 snprintf(tmp, sizeof(tmp), "%u", getppid());
1191 Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL);
1193 if (makelevel > 0) {
1195 snprintf(pn, sizeof(pn), "%s[%d]", progname, makelevel);
1196 progname = bmake_strdup(pn);
1202 Dir_Init(NULL); /* Dir_* safe to call from MainParseArgs */
1205 * First snag any flags out of the MAKE environment variable.
1206 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
1207 * in a different format).
1210 p1 = explode(getenv("MAKEFLAGS"));
1211 Main_ParseArgLine(p1);
1214 Main_ParseArgLine(getenv("MAKE"));
1218 * Find where we are (now).
1219 * We take care of PWD for the automounter below...
1221 if (getcwd(curdir, MAXPATHLEN) == NULL) {
1222 (void)fprintf(stderr, "%s: getcwd: %s.\n",
1223 progname, strerror(errno));
1227 MainParseArgs(argc, argv);
1230 printf("%s: Entering directory `%s'\n", progname, curdir);
1233 * Verify that cwd is sane.
1235 if (stat(curdir, &sa) == -1) {
1236 (void)fprintf(stderr, "%s: %s: %s.\n",
1237 progname, curdir, strerror(errno));
1242 * All this code is so that we know where we are when we start up
1243 * on a different machine with pmake.
1244 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
1245 * since the value of curdir can vary depending on how we got
1246 * here. Ie sitting at a shell prompt (shell that provides $PWD)
1247 * or via subdir.mk in which case its likely a shell which does
1249 * So, to stop it breaking this case only, we ignore PWD if
1250 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
1252 #ifndef NO_PWD_OVERRIDE
1254 char *pwd, *ptmp1 = NULL, *ptmp2 = NULL;
1256 if ((pwd = getenv("PWD")) != NULL &&
1257 Var_Value("MAKEOBJDIRPREFIX", VAR_CMD, &ptmp1) == NULL) {
1258 const char *makeobjdir = Var_Value("MAKEOBJDIR",
1261 if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
1262 if (stat(pwd, &sb) == 0 &&
1263 sa.st_ino == sb.st_ino &&
1264 sa.st_dev == sb.st_dev)
1265 (void)strncpy(curdir, pwd, MAXPATHLEN);
1272 Var_Set(".CURDIR", curdir, VAR_GLOBAL);
1275 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
1276 * MAKEOBJDIR is set in the environment, try only that value
1277 * and fall back to .CURDIR if it does not exist.
1279 * Otherwise, try _PATH_OBJDIR.MACHINE-MACHINE_ARCH, _PATH_OBJDIR.MACHINE,
1280 * and * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
1281 * of these paths exist, just use .CURDIR.
1284 (void)Main_SetObjdir("%s", curdir);
1286 if (!Main_SetVarObjdir("MAKEOBJDIRPREFIX", curdir) &&
1287 !Main_SetVarObjdir("MAKEOBJDIR", "") &&
1288 !Main_SetObjdir("%s.%s-%s", _PATH_OBJDIR, machine, machine_arch) &&
1289 !Main_SetObjdir("%s.%s", _PATH_OBJDIR, machine) &&
1290 !Main_SetObjdir("%s", _PATH_OBJDIR))
1291 (void)Main_SetObjdir("%s%s", _PATH_OBJDIRPREFIX, curdir);
1294 * Initialize archive, target and suffix modules in preparation for
1295 * parsing the makefile(s)
1300 Trace_Init(tracefile);
1305 Trace_Log(MAKESTART, NULL);
1308 * Set up the .TARGETS variable to contain the list of targets to be
1309 * created. If none specified, make the variable empty -- the parser
1310 * will fill the thing in with the default or .MAIN target.
1312 if (!Lst_IsEmpty(create)) {
1315 for (ln = Lst_First(create); ln != NULL;
1316 ln = Lst_Succ(ln)) {
1317 char *name = (char *)Lst_Datum(ln);
1319 Var_Append(".TARGETS", name, VAR_GLOBAL);
1322 Var_Set(".TARGETS", "", VAR_GLOBAL);
1326 * If no user-supplied system path was given (through the -m option)
1327 * add the directories from the DEFSYSPATH (more than one may be given
1328 * as dir1:...:dirn) to the system include path.
1330 if (syspath == NULL || *syspath == '\0')
1331 syspath = defsyspath;
1333 syspath = bmake_strdup(syspath);
1335 for (start = syspath; *start != '\0'; start = cp) {
1336 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1341 /* look for magic parent directory search string */
1342 if (strncmp(".../", start, 4) != 0) {
1343 (void)Dir_AddDir(defIncPath, start);
1345 if (Dir_FindHereOrAbove(curdir, start+4,
1346 found_path, sizeof(found_path))) {
1347 (void)Dir_AddDir(defIncPath, found_path);
1351 if (syspath != defsyspath)
1355 * Read in the built-in rules first, followed by the specified
1356 * makefile, if it was (makefile != NULL), or the default
1357 * makefile and Makefile, in that order, if it wasn't.
1362 sysMkPath = Lst_Init(FALSE);
1363 Dir_Expand(_PATH_DEFSYSMK,
1364 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
1366 if (Lst_IsEmpty(sysMkPath))
1367 Fatal("%s: no system rules (%s).", progname,
1369 ln = Lst_Find(sysMkPath, NULL, ReadMakefile);
1371 Fatal("%s: cannot open %s.", progname,
1372 (char *)Lst_Datum(ln));
1375 if (!Lst_IsEmpty(makefiles)) {
1378 ln = Lst_Find(makefiles, NULL, ReadAllMakefiles);
1380 Fatal("%s: cannot open %s.", progname,
1381 (char *)Lst_Datum(ln));
1383 p1 = Var_Subst(NULL, "${" MAKEFILE_PREFERENCE "}",
1384 VAR_CMD, VARF_WANTRES);
1386 (void)str2Lst_Append(makefiles, p1, NULL);
1387 (void)Lst_Find(makefiles, NULL, ReadMakefile);
1392 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1393 if (!noBuiltins || !printVars) {
1394 makeDependfile = Var_Subst(NULL, "${.MAKE.DEPENDFILE:T}",
1395 VAR_CMD, VARF_WANTRES);
1396 doing_depend = TRUE;
1397 (void)ReadMakefile(makeDependfile, NULL);
1398 doing_depend = FALSE;
1402 printf("%s: Entering directory `%s'\n", progname, objdir);
1406 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
1409 if (!forceJobs && !compatMake &&
1410 Var_Exists(".MAKE.JOBS", VAR_GLOBAL)) {
1414 value = Var_Subst(NULL, "${.MAKE.JOBS}", VAR_GLOBAL, VARF_WANTRES);
1415 n = strtol(value, NULL, 0);
1417 (void)fprintf(stderr, "%s: illegal value for .MAKE.JOBS -- must be positive integer!\n",
1422 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
1423 Var_Append(MAKEFLAGS, value, VAR_GLOBAL);
1426 maxJobTokens = maxJobs;
1432 * Be compatible if user did not specify -j and did not explicitly
1433 * turned compatibility on
1435 if (!compatMake && !forceJobs) {
1440 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1442 fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1443 jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
1446 Main_ExportMAKEFLAGS(TRUE); /* initial export */
1450 * For compatibility, look at the directories in the VPATH variable
1451 * and add them to the search path, if the variable is defined. The
1452 * variable's value is in the same format as the PATH envariable, i.e.
1453 * <directory>:<directory>:<directory>...
1455 if (Var_Exists("VPATH", VAR_CMD)) {
1458 * GCC stores string constants in read-only memory, but
1459 * Var_Subst will want to write this thing, so store it
1462 static char VPATH[] = "${VPATH}";
1464 vpath = Var_Subst(NULL, VPATH, VAR_CMD, VARF_WANTRES);
1467 /* skip to end of directory */
1468 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1470 /* Save terminator character so know when to stop */
1473 /* Add directory to search path */
1474 (void)Dir_AddDir(dirSearchPath, path);
1477 } while (savec == ':');
1482 * Now that all search paths have been read for suffixes et al, it's
1483 * time to add the default search path to their lists...
1488 * Propagate attributes through :: dependency lists.
1492 /* print the initial graph, if the user requested it */
1496 /* print the values of any variables requested by the user */
1501 outOfDate = runTargets();
1505 Lst_Destroy(variables, NULL);
1506 Lst_Destroy(makefiles, NULL);
1507 Lst_Destroy(create, (FreeProc *)free);
1510 /* print the graph now it's been processed if the user requested it */
1514 Trace_Log(MAKEEND, 0);
1517 printf("%s: Leaving directory `%s'\n", progname, objdir);
1519 printf("%s: Leaving directory `%s'\n", progname, curdir);
1533 return outOfDate ? 1 : 0;
1538 * Open and parse the given makefile.
1541 * 0 if ok. -1 if couldn't open file.
1547 ReadMakefile(const void *p, const void *q MAKE_ATTR_UNUSED)
1549 const char *fname = p; /* makefile to read */
1551 size_t len = MAXPATHLEN;
1552 char *name, *path = bmake_malloc(len);
1554 if (!strcmp(fname, "-")) {
1555 Parse_File(NULL /*stdin*/, -1);
1556 Var_Set("MAKEFILE", "", VAR_INTERNAL);
1558 /* if we've chdir'd, rebuild the path name */
1559 if (strcmp(curdir, objdir) && *fname != '/') {
1560 size_t plen = strlen(curdir) + strlen(fname) + 2;
1562 path = bmake_realloc(path, len = 2 * plen);
1564 (void)snprintf(path, len, "%s/%s", curdir, fname);
1565 fd = open(path, O_RDONLY);
1571 /* If curdir failed, try objdir (ala .depend) */
1572 plen = strlen(objdir) + strlen(fname) + 2;
1574 path = bmake_realloc(path, len = 2 * plen);
1575 (void)snprintf(path, len, "%s/%s", objdir, fname);
1576 fd = open(path, O_RDONLY);
1582 fd = open(fname, O_RDONLY);
1586 /* look in -I and system include directories. */
1587 name = Dir_FindFile(fname, parseIncPath);
1589 name = Dir_FindFile(fname,
1590 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1591 if (!name || (fd = open(name, O_RDONLY)) == -1) {
1598 * set the MAKEFILE variable desired by System V fans -- the
1599 * placement of the setting here means it gets set to the last
1600 * makefile specified, as it is set by SysV make.
1604 Var_Set("MAKEFILE", fname, VAR_INTERNAL);
1605 Parse_File(fname, fd);
1615 * Execute the command in cmd, and return the output of that command
1619 * A string containing the output of the command, or the empty string
1620 * If errnum is not NULL, it contains the reason for the command failure
1623 * The string must be freed by the caller.
1626 Cmd_Exec(const char *cmd, const char **errnum)
1628 const char *args[4]; /* Args for invoking the shell */
1629 int fds[2]; /* Pipe streams */
1630 int cpid; /* Child PID */
1631 int pid; /* PID from wait() */
1632 char *res; /* result */
1633 WAIT_T status; /* command exit status */
1634 Buffer buf; /* buffer to store the result */
1636 int cc; /* bytes read, or -1 */
1637 int savederr; /* saved errno */
1645 * Set up arguments for shell
1647 args[0] = shellName;
1653 * Open a pipe for fetching its output
1655 if (pipe(fds) == -1) {
1656 *errnum = "Couldn't create pipe for \"%s\"";
1663 switch (cpid = vFork()) {
1666 * Close input side of pipe
1668 (void)close(fds[0]);
1671 * Duplicate the output stream to the shell's output, then
1672 * shut the extra thing down. Note we don't fetch the error
1673 * stream...why not? Why?
1675 (void)dup2(fds[1], 1);
1676 (void)close(fds[1]);
1680 (void)execv(shellPath, UNCONST(args));
1685 *errnum = "Couldn't exec \"%s\"";
1690 * No need for the writing half
1692 (void)close(fds[1]);
1698 char result[BUFSIZ];
1699 cc = read(fds[0], result, sizeof(result));
1701 Buf_AddBytes(&buf, cc, result);
1703 while (cc > 0 || (cc == -1 && errno == EINTR));
1708 * Close the input side of the pipe.
1710 (void)close(fds[0]);
1713 * Wait for the process to exit.
1715 while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) {
1716 JobReapChild(pid, status, FALSE);
1719 cc = Buf_Size(&buf);
1720 res = Buf_Destroy(&buf, FALSE);
1723 *errnum = "Couldn't read shell's output for \"%s\"";
1725 if (WIFSIGNALED(status))
1726 *errnum = "\"%s\" exited on a signal";
1727 else if (WEXITSTATUS(status) != 0)
1728 *errnum = "\"%s\" returned non-zero status";
1731 * Null-terminate the result, convert newlines to spaces and
1732 * install it in the variable.
1737 if (cc > 0 && *--cp == '\n') {
1739 * A final newline is just stripped
1753 res = bmake_malloc(1);
1760 * Print an error message given its format.
1766 * The message is printed.
1770 Error(const char *fmt, ...)
1775 err_file = debug_file;
1776 if (err_file == stdout)
1778 (void)fflush(stdout);
1781 fprintf(err_file, "%s: ", progname);
1782 (void)vfprintf(err_file, fmt, ap);
1784 (void)fprintf(err_file, "\n");
1785 (void)fflush(err_file);
1786 if (err_file == stderr)
1794 * Produce a Fatal error message. If jobs are running, waits for them
1805 Fatal(const char *fmt, ...)
1813 (void)fflush(stdout);
1814 (void)vfprintf(stderr, fmt, ap);
1816 (void)fprintf(stderr, "\n");
1817 (void)fflush(stderr);
1819 PrintOnError(NULL, NULL);
1821 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1823 Trace_Log(MAKEERROR, 0);
1824 exit(2); /* Not 1 so -q can distinguish error */
1829 * Major exception once jobs are being created. Kills all jobs, prints
1830 * a message and exits.
1836 * All children are killed indiscriminately and the program Lib_Exits
1840 Punt(const char *fmt, ...)
1845 (void)fflush(stdout);
1846 (void)fprintf(stderr, "%s: ", progname);
1847 (void)vfprintf(stderr, fmt, ap);
1849 (void)fprintf(stderr, "\n");
1850 (void)fflush(stderr);
1852 PrintOnError(NULL, NULL);
1859 * Exit without giving a message.
1874 Trace_Log(MAKEERROR, 0);
1875 exit(2); /* Not 1, so -q can distinguish error */
1880 * Called when aborting due to errors in child shell to signal
1891 /* number of errors encountered in Make_Make */
1893 if (dieQuietly(NULL, -1))
1895 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1900 * Remove a file carefully, avoiding directories.
1903 eunlink(const char *file)
1907 if (lstat(file, &st) == -1)
1910 if (S_ISDIR(st.st_mode)) {
1914 return unlink(file);
1919 * Print why exec failed, avoiding stdio.
1922 execError(const char *af, const char *av)
1926 struct iovec iov[8];
1928 (void)(iov[i].iov_base = UNCONST(s), \
1929 iov[i].iov_len = strlen(iov[i].iov_base), \
1932 #define IOADD(s) (void)write(2, s, strlen(s))
1940 IOADD(") failed (");
1941 IOADD(strerror(errno));
1945 while (writev(2, iov, 8) == -1 && errno == EAGAIN)
1952 * exit with usage message
1958 if ((p = strchr(progname, '[')) != NULL)
1961 (void)fprintf(stderr,
1962 "usage: %s [-BeikNnqrstWwX] \n\
1963 [-C directory] [-D variable] [-d flags] [-f makefile]\n\
1964 [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1965 [-V variable] [-v variable] [variable=value] [target ...]\n",
1971 * realpath(3) can get expensive, cache results...
1973 static GNode *cached_realpaths = NULL;
1976 get_cached_realpaths(void)
1979 if (!cached_realpaths) {
1980 cached_realpaths = Targ_NewGN("Realpath");
1981 #ifndef DEBUG_REALPATH_CACHE
1982 cached_realpaths->flags = INTERNAL;
1986 return cached_realpaths;
1989 /* purge any relative paths */
1991 purge_cached_realpaths(void)
1993 GNode *cache = get_cached_realpaths();
1994 Hash_Entry *he, *nhe;
1997 he = Hash_EnumFirst(&cache->context, &hs);
1999 nhe = Hash_EnumNext(&hs);
2000 if (he->name[0] != '/') {
2002 fprintf(stderr, "cached_realpath: purging %s\n", he->name);
2003 Hash_DeleteEntry(&cache->context, he);
2010 cached_realpath(const char *pathname, char *resolved)
2015 if (!pathname || !pathname[0])
2018 cache = get_cached_realpaths();
2020 if ((rp = Var_Value(pathname, cache, &cp)) != NULL) {
2022 strlcpy(resolved, rp, MAXPATHLEN);
2023 } else if ((rp = realpath(pathname, resolved)) != NULL) {
2024 Var_Set(pathname, rp, cache);
2025 } /* else should we negative-cache? */
2028 return rp ? resolved : NULL;
2032 PrintAddr(void *a, void *b)
2034 printf("%lx ", (unsigned long) a);
2040 addErrorCMD(void *cmdp, void *gnp MAKE_ATTR_UNUSED)
2043 return 1; /* stop */
2044 Var_Append(".ERROR_CMD", cmdp, VAR_GLOBAL);
2049 * Return true if we should die without noise.
2050 * For example our failing child was a sub-make
2051 * or failure happend elsewhere.
2054 dieQuietly(GNode *gn, int bf)
2056 static int quietly = -1;
2059 if (DEBUG(JOB) || getBoolean(".MAKE.DIE_QUIETLY", 1) == 0)
2064 quietly = (gn) ? ((gn->type & (OP_MAKE)) != 0) : 0;
2070 PrintOnError(GNode *gn, const char *s)
2072 static GNode *en = NULL;
2076 /* we generally want to keep quiet if a sub-make died */
2077 if (dieQuietly(gn, -1))
2083 printf("\n%s: stopped in %s\n", progname, curdir);
2086 return; /* we've been here! */
2089 * We can print this even if there is no .ERROR target.
2091 Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL);
2092 Var_Delete(".ERROR_CMD", VAR_GLOBAL);
2093 Lst_ForEach(gn->commands, addErrorCMD, gn);
2095 strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
2097 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, VARF_WANTRES);
2106 * Finally, see if there is a .ERROR target, and run it if so.
2108 en = Targ_FindNode(".ERROR", TARG_NOCREATE);
2110 en->type |= OP_SPECIAL;
2111 Compat_Make(en, en);
2116 Main_ExportMAKEFLAGS(Boolean first)
2118 static int once = 1;
2126 strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
2128 s = Var_Subst(NULL, tmp, VAR_CMD, VARF_WANTRES);
2131 setenv("MAKEFLAGS", s, 1);
2133 setenv("MAKE", s, 1);
2141 static char *tmpdir = NULL;
2147 * Honor $TMPDIR but only if it is valid.
2148 * Ensure it ends with /.
2150 tmpdir = Var_Subst(NULL, "${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL,
2152 if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
2154 tmpdir = bmake_strdup(_PATH_TMP);
2161 * Create and open a temp file using "pattern".
2162 * If "fnamep" is provided set it to a copy of the filename created.
2163 * Otherwise unlink the file once open.
2166 mkTempFile(const char *pattern, char **fnamep)
2168 static char *tmpdir = NULL;
2169 char tfile[MAXPATHLEN];
2175 tmpdir = getTmpdir();
2176 if (pattern[0] == '/') {
2177 snprintf(tfile, sizeof(tfile), "%s", pattern);
2179 snprintf(tfile, sizeof(tfile), "%s%s", tmpdir, pattern);
2181 if ((fd = mkstemp(tfile)) < 0)
2182 Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
2184 *fnamep = bmake_strdup(tfile);
2186 unlink(tfile); /* we just want the descriptor */
2192 * Convert a string representation of a boolean.
2193 * Anything that looks like "No", "False", "Off", "0" etc,
2194 * is FALSE, otherwise TRUE.
2197 s2Boolean(const char *s, Boolean bf)
2201 case '\0': /* not set - the default wins */
2231 * Return a Boolean based on setting of a knob.
2233 * If the knob is not set, the supplied default is the return value.
2234 * If set, anything that looks or smells like "No", "False", "Off", "0" etc,
2235 * is FALSE, otherwise TRUE.
2238 getBoolean(const char *name, Boolean bf)
2243 if (snprintf(tmp, sizeof(tmp), "${%s:U:tl}", name) < (int)(sizeof(tmp))) {
2244 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, VARF_WANTRES);
2247 bf = s2Boolean(cp, bf);