1 /* $NetBSD: main.c,v 1.272 2017/06/19 19:58:24 christos 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.272 2017/06/19 19:58:24 christos 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.272 2017/06/19 19:58:24 christos 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;
202 Boolean forceJobs = FALSE;
205 * On some systems MACHINE is defined as something other than
210 # define MACHINE FORCE_MACHINE
213 extern Lst parseIncPath;
216 * For compatibility with the POSIX version of MAKEFLAGS that includes
217 * all the options with out -, convert flags to -f -l -a -g -s.
220 explode(const char *flags)
229 for (f = flags; *f; f++)
230 if (!isalpha((unsigned char)*f))
234 return bmake_strdup(flags);
237 st = nf = bmake_malloc(len * 3 + 1);
248 parse_debug_options(const char *argvalue)
255 for (modules = argvalue; *modules; ++modules) {
273 debug |= DEBUG_ERROR;
279 if (modules[1] == '1') {
280 debug |= DEBUG_GRAPH1;
283 else if (modules[1] == '2') {
284 debug |= DEBUG_GRAPH2;
287 else if (modules[1] == '3') {
288 debug |= DEBUG_GRAPH3;
305 debug |= DEBUG_SCRIPT;
308 debug |= DEBUG_PARSE;
323 debug |= DEBUG_SHELL;
326 if (debug_file != stdout && debug_file != stderr)
328 if (*++modules == '+') {
333 if (strcmp(modules, "stdout") == 0) {
337 if (strcmp(modules, "stderr") == 0) {
341 len = strlen(modules);
342 fname = bmake_malloc(len + 20);
343 memcpy(fname, modules, len + 1);
344 /* Let the filename be modified by the pid */
345 if (strcmp(fname + len - 3, ".%d") == 0)
346 snprintf(fname + len - 2, 20, "%d", getpid());
347 debug_file = fopen(fname, mode);
349 fprintf(stderr, "Cannot open debug file %s\n",
356 (void)fprintf(stderr,
357 "%s: illegal argument to d option -- %c\n",
364 * Make the debug_file unbuffered, and make
365 * stdout line buffered (unless debugfile == stdout).
367 setvbuf(debug_file, NULL, _IONBF, 0);
368 if (debug_file != stdout) {
369 setvbuf(stdout, NULL, _IOLBF, 0);
374 * does path contain any relative components
377 is_relpath(const char *path)
385 cp = strstr(cp, "/.");
389 if (cp[0] == '/' || cp[0] == '\0')
391 else if (cp[0] == '.') {
392 if (cp[1] == '/' || cp[1] == '\0')
401 * Parse a given argument vector. Called from main() and from
402 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
404 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
410 * Various global and local flags will be set depending on the flags
414 MainParseArgs(int argc, char **argv)
420 const char *getopt_def;
423 Boolean inOption, dashDash = FALSE;
424 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
426 #define OPTFLAGS "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrstv:w"
427 /* Can't actually use getopt(3) because rescanning is not portable */
429 getopt_def = OPTFLAGS;
447 if (c != '-' || dashDash)
452 /* '-' found at some earlier point */
453 getopt_spec = strchr(getopt_def, c);
454 if(c != '\0' && getopt_spec != NULL && getopt_spec[1] == ':') {
455 /* -<something> found, and <something> should have an arg */
459 if(*argvalue == '\0') {
475 Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
476 Var_Set(MAKE_MODE, "compat", VAR_GLOBAL, 0);
479 if (chdir(argvalue) == -1) {
480 (void)fprintf(stderr,
481 "%s: chdir %s: %s\n",
486 if (getcwd(curdir, MAXPATHLEN) == NULL) {
487 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
490 if (!is_relpath(argvalue) &&
491 stat(argvalue, &sa) != -1 &&
492 stat(curdir, &sb) != -1 &&
493 sa.st_ino == sb.st_ino &&
494 sa.st_dev == sb.st_dev)
495 strncpy(curdir, argvalue, MAXPATHLEN);
499 if (argvalue == NULL || argvalue[0] == 0) goto noarg;
500 Var_Set(argvalue, "1", VAR_GLOBAL, 0);
501 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
502 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
505 if (argvalue == NULL) goto noarg;
506 Parse_AddIncludeDir(argvalue);
507 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
508 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
511 if (argvalue == NULL) goto noarg;
512 if (sscanf(argvalue, "%d,%d", &jp_0, &jp_1) != 2) {
513 (void)fprintf(stderr,
514 "%s: internal error -- J option malformed (%s)\n",
518 if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
519 (fcntl(jp_1, F_GETFD, 0) < 0)) {
521 (void)fprintf(stderr,
522 "%s: ###### warning -- J descriptors were closed!\n",
530 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
531 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
537 noRecursiveExecute = TRUE;
538 Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
542 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
545 if (argvalue == NULL) goto noarg;
546 tracefile = bmake_strdup(argvalue);
547 Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
548 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
552 if (argvalue == NULL) goto noarg;
553 printVars = c == 'v' ? EXPAND_VARS : COMPAT_VARS;
554 (void)Lst_AtEnd(variables, argvalue);
555 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
556 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
559 parseWarnFatal = TRUE;
562 varNoExportEnv = TRUE;
563 Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
566 if (argvalue == NULL) goto noarg;
567 /* If '-d-opts' don't pass to children */
568 if (argvalue[0] == '-')
571 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
572 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
574 parse_debug_options(argvalue);
577 checkEnvFirst = TRUE;
578 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
581 if (argvalue == NULL) goto noarg;
582 (void)Lst_AtEnd(makefiles, argvalue);
586 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
589 if (argvalue == NULL) goto noarg;
591 maxJobs = strtol(argvalue, &p, 0);
592 if (*p != '\0' || maxJobs < 1) {
593 (void)fprintf(stderr, "%s: illegal argument to -j -- must be positive integer!\n",
597 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
598 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
599 Var_Set(".MAKE.JOBS", argvalue, VAR_GLOBAL, 0);
600 maxJobTokens = maxJobs;
604 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
607 if (argvalue == NULL) goto noarg;
608 /* look for magic parent directory search string */
609 if (strncmp(".../", argvalue, 4) == 0) {
610 if (!Dir_FindHereOrAbove(curdir, argvalue+4,
611 found_path, sizeof(found_path)))
612 break; /* nothing doing */
613 (void)Dir_AddDir(sysIncPath, found_path);
615 (void)Dir_AddDir(sysIncPath, argvalue);
617 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
618 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
622 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
626 /* Kind of nonsensical, wot? */
627 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
631 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
635 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
639 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
643 Var_Append(MAKEFLAGS, "-w", VAR_GLOBAL);
651 fprintf(stderr, "getopt(%s) -> %d (%c)\n",
663 * See if the rest of the arguments are variable assignments and
664 * perform them if so. Else take them to be targets and stuff them
665 * on the end of the "create" list.
667 for (; argc > 1; ++argv, --argc)
668 if (Parse_IsVar(argv[1])) {
669 Parse_DoVar(argv[1], VAR_CMD);
672 Punt("illegal (null) argument.");
673 if (*argv[1] == '-' && !dashDash)
675 (void)Lst_AtEnd(create, bmake_strdup(argv[1]));
680 (void)fprintf(stderr, "%s: option requires an argument -- %c\n",
686 * Main_ParseArgLine --
687 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
688 * is encountered and by main() when reading the .MAKEFLAGS envariable.
689 * Takes a line of arguments and breaks it into its
690 * component words and passes those words and the number of them to the
691 * MainParseArgs function.
692 * The line should have all its leading whitespace removed.
695 * line Line to fracture
701 * Only those that come from the various arguments.
704 Main_ParseArgLine(const char *line)
706 char **argv; /* Manufactured argument vector */
707 int argc; /* Number of arguments in argv */
708 char *args; /* Space used by the args */
710 char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
715 for (; *line == ' '; ++line)
723 * $MAKE may simply be naming the make(1) binary
727 if (!(cp = strrchr(line, '/')))
729 if ((cp = strstr(cp, "make")) &&
730 strcmp(cp, "make") == 0)
734 buf = bmake_malloc(len = strlen(line) + strlen(argv0) + 2);
735 (void)snprintf(buf, len, "%s %s", argv0, line);
738 argv = brk_string(buf, &argc, TRUE, &args);
740 Error("Unterminated quoted string [%s]", buf);
745 MainParseArgs(argc, argv);
752 Main_SetObjdir(const char *fmt, ...)
756 char buf[MAXPATHLEN + 1];
757 char buf2[MAXPATHLEN + 1];
762 vsnprintf(path = buf, MAXPATHLEN, fmt, ap);
765 if (path[0] != '/') {
766 snprintf(buf2, MAXPATHLEN, "%s/%s", curdir, path);
770 /* look for the directory and try to chdir there */
771 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
773 (void)fprintf(stderr, "make warning: %s: %s.\n",
774 path, strerror(errno));
776 strncpy(objdir, path, MAXPATHLEN);
777 Var_Set(".OBJDIR", objdir, VAR_GLOBAL, 0);
778 setenv("PWD", objdir, 1);
780 purge_cached_realpaths();
782 if (enterFlag && strcmp(objdir, curdir) != 0)
791 Main_SetVarObjdir(const char *var, const char *suffix)
793 char *p, *path, *xpath;
795 if ((path = Var_Value(var, VAR_CMD, &p)) == NULL)
798 /* expand variable substitutions */
799 if (strchr(path, '$') != 0)
800 xpath = Var_Subst(NULL, path, VAR_GLOBAL, VARF_WANTRES);
804 (void)Main_SetObjdir("%s%s", xpath, suffix);
813 * ReadAllMakefiles --
814 * wrapper around ReadMakefile() to read all.
817 * TRUE if ok, FALSE on error
820 ReadAllMakefiles(const void *p, const void *q)
822 return (ReadMakefile(p, q) == 0);
826 str2Lst_Append(Lst lp, char *str, const char *sep)
834 for (n = 0, cp = strtok(str, sep); cp; cp = strtok(NULL, sep)) {
835 (void)Lst_AtEnd(lp, cp);
844 siginfo(int signo MAKE_ATTR_UNUSED)
846 char dir[MAXPATHLEN];
847 char str[2 * MAXPATHLEN];
849 if (getcwd(dir, sizeof(dir)) == NULL)
851 len = snprintf(str, sizeof(str), "%s: Working in: %s\n", progname, dir);
853 (void)write(STDERR_FILENO, str, (size_t)len);
858 * Allow makefiles some control over the mode we run in.
861 MakeMode(const char *mode)
866 mode = mp = Var_Subst(NULL, "${" MAKE_MODE ":tl}",
867 VAR_GLOBAL, VARF_WANTRES);
870 if (strstr(mode, "compat")) {
875 if (strstr(mode, "meta"))
876 meta_mode_init(mode);
889 if (printVars == EXPAND_VARS)
894 expandVars = getBoolean(".MAKE.EXPAND_VARIABLES", FALSE);
896 for (ln = Lst_First(variables); ln != NULL;
898 char *var = (char *)Lst_Datum(ln);
902 if (strchr(var, '$')) {
903 value = p1 = Var_Subst(NULL, var, VAR_GLOBAL,
905 } else if (expandVars) {
907 int len = snprintf(tmp, sizeof(tmp), "${%s}", var);
909 if (len >= (int)sizeof(tmp))
910 Fatal("%s: variable name too big: %s",
912 value = p1 = Var_Subst(NULL, tmp, VAR_GLOBAL,
915 value = Var_Value(var, VAR_GLOBAL, &p1);
917 printf("%s\n", value ? value : "");
925 Lst targs; /* target nodes to create -- passed to Make_Init */
926 Boolean outOfDate; /* FALSE if all targets up to date */
929 * Have now read the entire graph and need to make a list of
930 * targets to create. If none was given on the command line,
931 * we consult the parsing module to find the main target(s)
934 if (Lst_IsEmpty(create))
935 targs = Parse_MainName();
937 targs = Targ_FindList(create, TARG_CREATE);
941 * Initialize job module before traversing the graph
942 * now that any .BEGIN and .END targets have been read.
943 * This is done only if the -q flag wasn't given
944 * (to prevent the .BEGIN from being executed should
952 /* Traverse the graph, checking on all the targets */
953 outOfDate = Make_Run(targs);
956 * Compat_Init will take care of creating all the
957 * targets as well as initializing the module.
962 Lst_Destroy(targs, NULL);
968 * The main function, for obvious reasons. Initializes variables
969 * and a few modules, then parses the arguments give it in the
970 * environment and on the command line. Reads the system makefile
971 * followed by either Makefile, makefile or the file given by the
972 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
973 * flags it has received by then uses either the Make or the Compat
974 * module to create the initial list of targets.
977 * If -q was given, exits -1 if anything was out-of-date. Else it exits
981 * The program exits when done. Targets are created. etc. etc. etc.
984 main(int argc, char **argv)
986 Boolean outOfDate; /* FALSE if all targets up to date */
989 char mdpath[MAXPATHLEN];
991 const char *machine = FORCE_MACHINE;
993 const char *machine = getenv("MACHINE");
995 const char *machine_arch = getenv("MACHINE_ARCH");
996 char *syspath = getenv("MAKESYSPATH");
997 Lst sysMkPath; /* Path of sys.mk */
998 char *cp = NULL, *start;
999 /* avoid faults on read-only strings */
1000 static char defsyspath[] = _PATH_DEFSYSPATH;
1001 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
1002 struct timeval rightnow; /* to initialize random seed */
1003 struct utsname utsname;
1005 /* default to writing debug to stderr */
1006 debug_file = stderr;
1009 (void)bmake_signal(SIGINFO, siginfo);
1012 * Set the seed to produce a different random sequence
1013 * on each program execution.
1015 gettimeofday(&rightnow, NULL);
1016 srandom(rightnow.tv_sec + rightnow.tv_usec);
1018 if ((progname = strrchr(argv[0], '/')) != NULL)
1022 #if defined(MAKE_NATIVE) || (defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE))
1024 * get rid of resource limit on file descriptors
1028 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
1029 rl.rlim_cur != rl.rlim_max) {
1030 rl.rlim_cur = rl.rlim_max;
1031 (void)setrlimit(RLIMIT_NOFILE, &rl);
1036 if (uname(&utsname) == -1) {
1037 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
1043 * Get the name of this type of MACHINE from utsname
1044 * so we can share an executable for similar machines.
1045 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
1047 * Note that both MACHINE and MACHINE_ARCH are decided at
1052 machine = utsname.machine;
1055 machine = MAKE_MACHINE;
1057 machine = "unknown";
1062 if (!machine_arch) {
1063 #if defined(MAKE_NATIVE) && defined(HAVE_SYSCTL) && defined(CTL_HW) && defined(HW_MACHINE_ARCH)
1064 static char machine_arch_buf[sizeof(utsname.machine)];
1065 int mib[2] = { CTL_HW, HW_MACHINE_ARCH };
1066 size_t len = sizeof(machine_arch_buf);
1068 if (sysctl(mib, __arraycount(mib), machine_arch_buf,
1069 &len, NULL, 0) < 0) {
1070 (void)fprintf(stderr, "%s: sysctl failed (%s).\n", progname,
1075 machine_arch = machine_arch_buf;
1077 #ifndef MACHINE_ARCH
1078 #ifdef MAKE_MACHINE_ARCH
1079 machine_arch = MAKE_MACHINE_ARCH;
1081 machine_arch = "unknown";
1084 machine_arch = MACHINE_ARCH;
1089 myPid = getpid(); /* remember this for vFork() */
1092 * Just in case MAKEOBJDIR wants us to do something tricky.
1094 Var_Init(); /* Initialize the lists of variables for
1095 * parsing arguments */
1096 Var_Set(".MAKE.OS", utsname.sysname, VAR_GLOBAL, 0);
1097 Var_Set("MACHINE", machine, VAR_GLOBAL, 0);
1098 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL, 0);
1100 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL, 0);
1102 Var_Set(".newline", "\n", VAR_GLOBAL, 0); /* handy for :@ loops */
1104 * This is the traditional preference for makefiles.
1106 #ifndef MAKEFILE_PREFERENCE_LIST
1107 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
1109 Var_Set(MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST,
1111 Var_Set(MAKE_DEPENDFILE, ".depend", VAR_GLOBAL, 0);
1113 create = Lst_Init(FALSE);
1114 makefiles = Lst_Init(FALSE);
1117 variables = Lst_Init(FALSE);
1118 beSilent = FALSE; /* Print commands as executed */
1119 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
1120 noExecute = FALSE; /* Execute all commands */
1121 noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
1122 keepgoing = FALSE; /* Stop on error */
1123 allPrecious = FALSE; /* Remove targets when interrupted */
1124 deleteOnError = FALSE; /* Historical default behavior */
1125 queryFlag = FALSE; /* This is not just a check-run */
1126 noBuiltins = FALSE; /* Read the built-in rules */
1127 touchFlag = FALSE; /* Actually update targets */
1128 debug = 0; /* No debug verbosity, please. */
1129 jobsRunning = FALSE;
1131 maxJobs = DEFMAXLOCAL; /* Set default local max concurrency */
1132 maxJobTokens = maxJobs;
1133 compatMake = FALSE; /* No compat mode */
1137 * Initialize the parsing, directory and variable modules to prepare
1138 * for the reading of inclusion paths and variable settings on the
1143 * Initialize various variables.
1144 * MAKE also gets this name, for compatibility
1145 * .MAKEFLAGS gets set to the empty string just in case.
1146 * MFLAGS also gets initialized empty, for compatibility.
1149 if (argv[0][0] == '/' || strchr(argv[0], '/') == NULL) {
1151 * Leave alone if it is an absolute path, or if it does
1152 * not contain a '/' in which case we need to find it in
1153 * the path, like execvp(3) and the shells do.
1158 * A relative path, canonicalize it.
1160 p1 = cached_realpath(argv[0], mdpath);
1161 if (!p1 || *p1 != '/' || stat(p1, &sb) < 0) {
1162 p1 = argv[0]; /* realpath failed */
1165 Var_Set("MAKE", p1, VAR_GLOBAL, 0);
1166 Var_Set(".MAKE", p1, VAR_GLOBAL, 0);
1167 Var_Set(MAKEFLAGS, "", VAR_GLOBAL, 0);
1168 Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL, 0);
1169 Var_Set("MFLAGS", "", VAR_GLOBAL, 0);
1170 Var_Set(".ALLTARGETS", "", VAR_GLOBAL, 0);
1171 /* some makefiles need to know this */
1172 Var_Set(MAKE_LEVEL ".ENV", MAKE_LEVEL_ENV, VAR_CMD, 0);
1175 * Set some other useful macros
1180 makelevel = ((ep = getenv(MAKE_LEVEL_ENV)) && *ep) ? atoi(ep) : 0;
1183 snprintf(tmp, sizeof(tmp), "%d", makelevel);
1184 Var_Set(MAKE_LEVEL, tmp, VAR_GLOBAL, 0);
1185 snprintf(tmp, sizeof(tmp), "%u", myPid);
1186 Var_Set(".MAKE.PID", tmp, VAR_GLOBAL, 0);
1187 snprintf(tmp, sizeof(tmp), "%u", getppid());
1188 Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL, 0);
1190 if (makelevel > 0) {
1192 snprintf(pn, sizeof(pn), "%s[%d]", progname, makelevel);
1193 progname = bmake_strdup(pn);
1199 Dir_Init(NULL); /* Dir_* safe to call from MainParseArgs */
1202 * First snag any flags out of the MAKE environment variable.
1203 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
1204 * in a different format).
1207 p1 = explode(getenv("MAKEFLAGS"));
1208 Main_ParseArgLine(p1);
1211 Main_ParseArgLine(getenv("MAKE"));
1215 * Find where we are (now).
1216 * We take care of PWD for the automounter below...
1218 if (getcwd(curdir, MAXPATHLEN) == NULL) {
1219 (void)fprintf(stderr, "%s: getcwd: %s.\n",
1220 progname, strerror(errno));
1224 MainParseArgs(argc, argv);
1227 printf("%s: Entering directory `%s'\n", progname, curdir);
1230 * Verify that cwd is sane.
1232 if (stat(curdir, &sa) == -1) {
1233 (void)fprintf(stderr, "%s: %s: %s.\n",
1234 progname, curdir, strerror(errno));
1239 * All this code is so that we know where we are when we start up
1240 * on a different machine with pmake.
1241 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
1242 * since the value of curdir can vary depending on how we got
1243 * here. Ie sitting at a shell prompt (shell that provides $PWD)
1244 * or via subdir.mk in which case its likely a shell which does
1246 * So, to stop it breaking this case only, we ignore PWD if
1247 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
1249 #ifndef NO_PWD_OVERRIDE
1251 char *pwd, *ptmp1 = NULL, *ptmp2 = NULL;
1253 if ((pwd = getenv("PWD")) != NULL &&
1254 Var_Value("MAKEOBJDIRPREFIX", VAR_CMD, &ptmp1) == NULL) {
1255 const char *makeobjdir = Var_Value("MAKEOBJDIR",
1258 if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
1259 if (stat(pwd, &sb) == 0 &&
1260 sa.st_ino == sb.st_ino &&
1261 sa.st_dev == sb.st_dev)
1262 (void)strncpy(curdir, pwd, MAXPATHLEN);
1269 Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0);
1272 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
1273 * MAKEOBJDIR is set in the environment, try only that value
1274 * and fall back to .CURDIR if it does not exist.
1276 * Otherwise, try _PATH_OBJDIR.MACHINE-MACHINE_ARCH, _PATH_OBJDIR.MACHINE,
1277 * and * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
1278 * of these paths exist, just use .CURDIR.
1281 (void)Main_SetObjdir("%s", curdir);
1283 if (!Main_SetVarObjdir("MAKEOBJDIRPREFIX", curdir) &&
1284 !Main_SetVarObjdir("MAKEOBJDIR", "") &&
1285 !Main_SetObjdir("%s.%s-%s", _PATH_OBJDIR, machine, machine_arch) &&
1286 !Main_SetObjdir("%s.%s", _PATH_OBJDIR, machine) &&
1287 !Main_SetObjdir("%s", _PATH_OBJDIR))
1288 (void)Main_SetObjdir("%s%s", _PATH_OBJDIRPREFIX, curdir);
1291 * Initialize archive, target and suffix modules in preparation for
1292 * parsing the makefile(s)
1297 Trace_Init(tracefile);
1302 Trace_Log(MAKESTART, NULL);
1305 * Set up the .TARGETS variable to contain the list of targets to be
1306 * created. If none specified, make the variable empty -- the parser
1307 * will fill the thing in with the default or .MAIN target.
1309 if (!Lst_IsEmpty(create)) {
1312 for (ln = Lst_First(create); ln != NULL;
1313 ln = Lst_Succ(ln)) {
1314 char *name = (char *)Lst_Datum(ln);
1316 Var_Append(".TARGETS", name, VAR_GLOBAL);
1319 Var_Set(".TARGETS", "", VAR_GLOBAL, 0);
1323 * If no user-supplied system path was given (through the -m option)
1324 * add the directories from the DEFSYSPATH (more than one may be given
1325 * as dir1:...:dirn) to the system include path.
1327 if (syspath == NULL || *syspath == '\0')
1328 syspath = defsyspath;
1330 syspath = bmake_strdup(syspath);
1332 for (start = syspath; *start != '\0'; start = cp) {
1333 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1338 /* look for magic parent directory search string */
1339 if (strncmp(".../", start, 4) != 0) {
1340 (void)Dir_AddDir(defIncPath, start);
1342 if (Dir_FindHereOrAbove(curdir, start+4,
1343 found_path, sizeof(found_path))) {
1344 (void)Dir_AddDir(defIncPath, found_path);
1348 if (syspath != defsyspath)
1352 * Read in the built-in rules first, followed by the specified
1353 * makefile, if it was (makefile != NULL), or the default
1354 * makefile and Makefile, in that order, if it wasn't.
1359 sysMkPath = Lst_Init(FALSE);
1360 Dir_Expand(_PATH_DEFSYSMK,
1361 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
1363 if (Lst_IsEmpty(sysMkPath))
1364 Fatal("%s: no system rules (%s).", progname,
1366 ln = Lst_Find(sysMkPath, NULL, ReadMakefile);
1368 Fatal("%s: cannot open %s.", progname,
1369 (char *)Lst_Datum(ln));
1372 if (!Lst_IsEmpty(makefiles)) {
1375 ln = Lst_Find(makefiles, NULL, ReadAllMakefiles);
1377 Fatal("%s: cannot open %s.", progname,
1378 (char *)Lst_Datum(ln));
1380 p1 = Var_Subst(NULL, "${" MAKEFILE_PREFERENCE "}",
1381 VAR_CMD, VARF_WANTRES);
1383 (void)str2Lst_Append(makefiles, p1, NULL);
1384 (void)Lst_Find(makefiles, NULL, ReadMakefile);
1389 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1390 if (!noBuiltins || !printVars) {
1391 makeDependfile = Var_Subst(NULL, "${.MAKE.DEPENDFILE:T}",
1392 VAR_CMD, VARF_WANTRES);
1393 doing_depend = TRUE;
1394 (void)ReadMakefile(makeDependfile, NULL);
1395 doing_depend = FALSE;
1399 printf("%s: Entering directory `%s'\n", progname, objdir);
1403 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
1406 if (!forceJobs && !compatMake &&
1407 Var_Exists(".MAKE.JOBS", VAR_GLOBAL)) {
1411 value = Var_Subst(NULL, "${.MAKE.JOBS}", VAR_GLOBAL, VARF_WANTRES);
1412 n = strtol(value, NULL, 0);
1414 (void)fprintf(stderr, "%s: illegal value for .MAKE.JOBS -- must be positive integer!\n",
1419 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
1420 Var_Append(MAKEFLAGS, value, VAR_GLOBAL);
1423 maxJobTokens = maxJobs;
1429 * Be compatible if user did not specify -j and did not explicitly
1430 * turned compatibility on
1432 if (!compatMake && !forceJobs) {
1437 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1439 fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1440 jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
1443 Main_ExportMAKEFLAGS(TRUE); /* initial export */
1446 * For compatibility, look at the directories in the VPATH variable
1447 * and add them to the search path, if the variable is defined. The
1448 * variable's value is in the same format as the PATH envariable, i.e.
1449 * <directory>:<directory>:<directory>...
1451 if (Var_Exists("VPATH", VAR_CMD)) {
1454 * GCC stores string constants in read-only memory, but
1455 * Var_Subst will want to write this thing, so store it
1458 static char VPATH[] = "${VPATH}";
1460 vpath = Var_Subst(NULL, VPATH, VAR_CMD, VARF_WANTRES);
1463 /* skip to end of directory */
1464 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1466 /* Save terminator character so know when to stop */
1469 /* Add directory to search path */
1470 (void)Dir_AddDir(dirSearchPath, path);
1473 } while (savec == ':');
1478 * Now that all search paths have been read for suffixes et al, it's
1479 * time to add the default search path to their lists...
1484 * Propagate attributes through :: dependency lists.
1488 /* print the initial graph, if the user requested it */
1492 /* print the values of any variables requested by the user */
1497 outOfDate = runTargets();
1501 Lst_Destroy(variables, NULL);
1502 Lst_Destroy(makefiles, NULL);
1503 Lst_Destroy(create, (FreeProc *)free);
1506 /* print the graph now it's been processed if the user requested it */
1510 Trace_Log(MAKEEND, 0);
1513 printf("%s: Leaving directory `%s'\n", progname, objdir);
1515 printf("%s: Leaving directory `%s'\n", progname, curdir);
1529 return outOfDate ? 1 : 0;
1534 * Open and parse the given makefile.
1537 * 0 if ok. -1 if couldn't open file.
1543 ReadMakefile(const void *p, const void *q MAKE_ATTR_UNUSED)
1545 const char *fname = p; /* makefile to read */
1547 size_t len = MAXPATHLEN;
1548 char *name, *path = bmake_malloc(len);
1550 if (!strcmp(fname, "-")) {
1551 Parse_File(NULL /*stdin*/, -1);
1552 Var_Set("MAKEFILE", "", VAR_INTERNAL, 0);
1554 /* if we've chdir'd, rebuild the path name */
1555 if (strcmp(curdir, objdir) && *fname != '/') {
1556 size_t plen = strlen(curdir) + strlen(fname) + 2;
1558 path = bmake_realloc(path, len = 2 * plen);
1560 (void)snprintf(path, len, "%s/%s", curdir, fname);
1561 fd = open(path, O_RDONLY);
1567 /* If curdir failed, try objdir (ala .depend) */
1568 plen = strlen(objdir) + strlen(fname) + 2;
1570 path = bmake_realloc(path, len = 2 * plen);
1571 (void)snprintf(path, len, "%s/%s", objdir, fname);
1572 fd = open(path, O_RDONLY);
1578 fd = open(fname, O_RDONLY);
1582 /* look in -I and system include directories. */
1583 name = Dir_FindFile(fname, parseIncPath);
1585 name = Dir_FindFile(fname,
1586 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1587 if (!name || (fd = open(name, O_RDONLY)) == -1) {
1594 * set the MAKEFILE variable desired by System V fans -- the
1595 * placement of the setting here means it gets set to the last
1596 * makefile specified, as it is set by SysV make.
1600 Var_Set("MAKEFILE", fname, VAR_INTERNAL, 0);
1601 Parse_File(fname, fd);
1611 * Execute the command in cmd, and return the output of that command
1615 * A string containing the output of the command, or the empty string
1616 * If errnum is not NULL, it contains the reason for the command failure
1619 * The string must be freed by the caller.
1622 Cmd_Exec(const char *cmd, const char **errnum)
1624 const char *args[4]; /* Args for invoking the shell */
1625 int fds[2]; /* Pipe streams */
1626 int cpid; /* Child PID */
1627 int pid; /* PID from wait() */
1628 char *res; /* result */
1629 WAIT_T status; /* command exit status */
1630 Buffer buf; /* buffer to store the result */
1632 int cc; /* bytes read, or -1 */
1633 int savederr; /* saved errno */
1641 * Set up arguments for shell
1643 args[0] = shellName;
1649 * Open a pipe for fetching its output
1651 if (pipe(fds) == -1) {
1652 *errnum = "Couldn't create pipe for \"%s\"";
1659 switch (cpid = vFork()) {
1662 * Close input side of pipe
1664 (void)close(fds[0]);
1667 * Duplicate the output stream to the shell's output, then
1668 * shut the extra thing down. Note we don't fetch the error
1669 * stream...why not? Why?
1671 (void)dup2(fds[1], 1);
1672 (void)close(fds[1]);
1676 (void)execv(shellPath, UNCONST(args));
1681 *errnum = "Couldn't exec \"%s\"";
1686 * No need for the writing half
1688 (void)close(fds[1]);
1694 char result[BUFSIZ];
1695 cc = read(fds[0], result, sizeof(result));
1697 Buf_AddBytes(&buf, cc, result);
1699 while (cc > 0 || (cc == -1 && errno == EINTR));
1704 * Close the input side of the pipe.
1706 (void)close(fds[0]);
1709 * Wait for the process to exit.
1711 while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) {
1712 JobReapChild(pid, status, FALSE);
1715 cc = Buf_Size(&buf);
1716 res = Buf_Destroy(&buf, FALSE);
1719 *errnum = "Couldn't read shell's output for \"%s\"";
1721 if (WIFSIGNALED(status))
1722 *errnum = "\"%s\" exited on a signal";
1723 else if (WEXITSTATUS(status) != 0)
1724 *errnum = "\"%s\" returned non-zero status";
1727 * Null-terminate the result, convert newlines to spaces and
1728 * install it in the variable.
1733 if (cc > 0 && *--cp == '\n') {
1735 * A final newline is just stripped
1749 res = bmake_malloc(1);
1756 * Print an error message given its format.
1762 * The message is printed.
1766 Error(const char *fmt, ...)
1771 err_file = debug_file;
1772 if (err_file == stdout)
1774 (void)fflush(stdout);
1777 fprintf(err_file, "%s: ", progname);
1778 (void)vfprintf(err_file, fmt, ap);
1780 (void)fprintf(err_file, "\n");
1781 (void)fflush(err_file);
1782 if (err_file == stderr)
1790 * Produce a Fatal error message. If jobs are running, waits for them
1801 Fatal(const char *fmt, ...)
1809 (void)fflush(stdout);
1810 (void)vfprintf(stderr, fmt, ap);
1812 (void)fprintf(stderr, "\n");
1813 (void)fflush(stderr);
1815 PrintOnError(NULL, NULL);
1817 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1819 Trace_Log(MAKEERROR, 0);
1820 exit(2); /* Not 1 so -q can distinguish error */
1825 * Major exception once jobs are being created. Kills all jobs, prints
1826 * a message and exits.
1832 * All children are killed indiscriminately and the program Lib_Exits
1836 Punt(const char *fmt, ...)
1841 (void)fflush(stdout);
1842 (void)fprintf(stderr, "%s: ", progname);
1843 (void)vfprintf(stderr, fmt, ap);
1845 (void)fprintf(stderr, "\n");
1846 (void)fflush(stderr);
1848 PrintOnError(NULL, NULL);
1855 * Exit without giving a message.
1870 Trace_Log(MAKEERROR, 0);
1871 exit(2); /* Not 1, so -q can distinguish error */
1876 * Called when aborting due to errors in child shell to signal
1887 /* number of errors encountered in Make_Make */
1889 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1894 * Remove a file carefully, avoiding directories.
1897 eunlink(const char *file)
1901 if (lstat(file, &st) == -1)
1904 if (S_ISDIR(st.st_mode)) {
1908 return unlink(file);
1913 * Print why exec failed, avoiding stdio.
1916 execError(const char *af, const char *av)
1920 struct iovec iov[8];
1922 (void)(iov[i].iov_base = UNCONST(s), \
1923 iov[i].iov_len = strlen(iov[i].iov_base), \
1926 #define IOADD(s) (void)write(2, s, strlen(s))
1934 IOADD(") failed (");
1935 IOADD(strerror(errno));
1939 while (writev(2, iov, 8) == -1 && errno == EAGAIN)
1946 * exit with usage message
1952 if ((p = strchr(progname, '[')) != NULL)
1955 (void)fprintf(stderr,
1956 "usage: %s [-BeikNnqrstWwX] \n\
1957 [-C directory] [-D variable] [-d flags] [-f makefile]\n\
1958 [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1959 [-V variable] [-v variable] [variable=value] [target ...]\n",
1965 * realpath(3) can get expensive, cache results...
1967 static GNode *cached_realpaths = NULL;
1970 get_cached_realpaths(void)
1973 if (!cached_realpaths) {
1974 cached_realpaths = Targ_NewGN("Realpath");
1975 #ifndef DEBUG_REALPATH_CACHE
1976 cached_realpaths->flags = INTERNAL;
1980 return cached_realpaths;
1983 /* purge any relative paths */
1985 purge_cached_realpaths(void)
1987 GNode *cache = get_cached_realpaths();
1988 Hash_Entry *he, *nhe;
1991 he = Hash_EnumFirst(&cache->context, &hs);
1993 nhe = Hash_EnumNext(&hs);
1994 if (he->name[0] != '/') {
1996 fprintf(stderr, "cached_realpath: purging %s\n", he->name);
1997 Hash_DeleteEntry(&cache->context, he);
2004 cached_realpath(const char *pathname, char *resolved)
2009 if (!pathname || !pathname[0])
2012 cache = get_cached_realpaths();
2014 if ((rp = Var_Value(pathname, cache, &cp)) != NULL) {
2016 strlcpy(resolved, rp, MAXPATHLEN);
2017 } else if ((rp = realpath(pathname, resolved)) != NULL) {
2018 Var_Set(pathname, rp, cache, 0);
2021 return rp ? resolved : NULL;
2025 PrintAddr(void *a, void *b)
2027 printf("%lx ", (unsigned long) a);
2033 addErrorCMD(void *cmdp, void *gnp MAKE_ATTR_UNUSED)
2036 return 1; /* stop */
2037 Var_Append(".ERROR_CMD", cmdp, VAR_GLOBAL);
2042 PrintOnError(GNode *gn, const char *s)
2044 static GNode *en = NULL;
2051 printf("\n%s: stopped in %s\n", progname, curdir);
2054 return; /* we've been here! */
2057 * We can print this even if there is no .ERROR target.
2059 Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL, 0);
2060 Var_Delete(".ERROR_CMD", VAR_GLOBAL);
2061 Lst_ForEach(gn->commands, addErrorCMD, gn);
2063 strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
2065 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, VARF_WANTRES);
2074 * Finally, see if there is a .ERROR target, and run it if so.
2076 en = Targ_FindNode(".ERROR", TARG_NOCREATE);
2078 en->type |= OP_SPECIAL;
2079 Compat_Make(en, en);
2084 Main_ExportMAKEFLAGS(Boolean first)
2086 static int once = 1;
2094 strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
2096 s = Var_Subst(NULL, tmp, VAR_CMD, VARF_WANTRES);
2099 setenv("MAKEFLAGS", s, 1);
2101 setenv("MAKE", s, 1);
2109 static char *tmpdir = NULL;
2115 * Honor $TMPDIR but only if it is valid.
2116 * Ensure it ends with /.
2118 tmpdir = Var_Subst(NULL, "${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL,
2120 if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
2122 tmpdir = bmake_strdup(_PATH_TMP);
2129 * Create and open a temp file using "pattern".
2130 * If "fnamep" is provided set it to a copy of the filename created.
2131 * Otherwise unlink the file once open.
2134 mkTempFile(const char *pattern, char **fnamep)
2136 static char *tmpdir = NULL;
2137 char tfile[MAXPATHLEN];
2143 tmpdir = getTmpdir();
2144 if (pattern[0] == '/') {
2145 snprintf(tfile, sizeof(tfile), "%s", pattern);
2147 snprintf(tfile, sizeof(tfile), "%s%s", tmpdir, pattern);
2149 if ((fd = mkstemp(tfile)) < 0)
2150 Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
2152 *fnamep = bmake_strdup(tfile);
2154 unlink(tfile); /* we just want the descriptor */
2160 * Convert a string representation of a boolean.
2161 * Anything that looks like "No", "False", "Off", "0" etc,
2162 * is FALSE, otherwise TRUE.
2165 s2Boolean(const char *s, Boolean bf)
2169 case '\0': /* not set - the default wins */
2199 * Return a Boolean based on setting of a knob.
2201 * If the knob is not set, the supplied default is the return value.
2202 * If set, anything that looks or smells like "No", "False", "Off", "0" etc,
2203 * is FALSE, otherwise TRUE.
2206 getBoolean(const char *name, Boolean bf)
2211 if (snprintf(tmp, sizeof(tmp), "${%s:U:tl}", name) < (int)(sizeof(tmp))) {
2212 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, VARF_WANTRES);
2215 bf = s2Boolean(cp, bf);