1 /* $NetBSD: main.c,v 1.582 2022/05/07 17:49:47 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 * The main file for this entire program. Exit routines etc. reside here.
74 * Utility functions defined in this file:
77 * Parse and process command line arguments from a
78 * single string. Used to implement the special targets
79 * .MFLAGS and .MAKEFLAGS.
81 * Error Print a tagged error message.
83 * Fatal Print an error message and exit.
85 * Punt Abort all jobs and exit with a message.
87 * Finish Finish things up by printing the number of errors
88 * that occurred, and exit.
91 #include <sys/types.h>
93 #include <sys/param.h>
94 #include <sys/resource.h>
96 #if defined(MAKE_NATIVE) && defined(HAVE_SYSCTL)
97 #include <sys/sysctl.h>
99 #include <sys/utsname.h>
110 #include "pathnames.h"
113 /* "@(#)main.c 8.3 (Berkeley) 3/19/94" */
114 MAKE_RCSID("$NetBSD: main.c,v 1.582 2022/05/07 17:49:47 rillig Exp $");
115 #if defined(MAKE_NATIVE) && !defined(lint)
116 __COPYRIGHT("@(#) Copyright (c) 1988, 1989, 1990, 1993 "
117 "The Regents of the University of California. "
118 "All rights reserved.");
122 # define __arraycount(__x) (sizeof(__x) / sizeof(__x[0]))
126 time_t now; /* Time at start of make */
127 GNode *defaultNode; /* .DEFAULT node */
128 bool allPrecious; /* .PRECIOUS given on line by itself */
129 bool deleteOnError; /* .DELETE_ON_ERROR: set */
131 static int maxJobTokens; /* -j argument */
132 bool enterFlagObj; /* -w and objdir != srcdir */
134 static int jp_0 = -1, jp_1 = -1; /* ends of parent job pipe */
135 bool doing_depend; /* Set while reading .depend */
136 static bool jobsRunning; /* true if the jobs might be running */
137 static const char *tracefile;
138 static bool ReadMakefile(const char *);
139 static void purge_relative_cached_realpaths(void);
141 static bool ignorePWD; /* if we use -C, PWD is meaningless */
142 static char objdir[MAXPATHLEN + 1]; /* where we chdir'ed to */
143 char curdir[MAXPATHLEN + 1]; /* Startup directory */
144 const char *progname;
145 char *makeDependfile;
149 bool forceJobs = false;
150 static int main_errors = 0;
151 static HashTable cached_realpaths;
154 * For compatibility with the POSIX version of MAKEFLAGS that includes
155 * all the options without '-', convert 'flags' to '-f -l -a -g -s'.
158 explode(const char *flags)
166 for (p = flags; *p != '\0'; p++)
168 return bmake_strdup(flags);
170 exploded = bmake_malloc((size_t)(p - flags) * 3 + 1);
171 for (p = flags, ep = exploded; *p != '\0'; p++) {
180 MAKE_ATTR_DEAD static void
183 size_t prognameLen = strcspn(progname, "[");
185 (void)fprintf(stderr,
186 "usage: %.*s [-BeikNnqrSstWwX]\n"
187 " [-C directory] [-D variable] [-d flags] [-f makefile]\n"
188 " [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n"
189 " [-V variable] [-v variable] [variable=value] [target ...]\n",
190 (int)prognameLen, progname);
195 MainParseArgDebugFile(const char *arg)
201 if (opts.debug_file != stdout && opts.debug_file != stderr)
202 fclose(opts.debug_file);
210 if (strcmp(arg, "stdout") == 0) {
211 opts.debug_file = stdout;
214 if (strcmp(arg, "stderr") == 0) {
215 opts.debug_file = stderr;
220 fname = bmake_malloc(len + 20);
221 memcpy(fname, arg, len + 1);
223 /* Replace the trailing '%d' after '.%d' with the pid. */
224 if (len >= 3 && memcmp(fname + len - 3, ".%d", 3) == 0)
225 snprintf(fname + len - 2, 20, "%d", getpid());
227 opts.debug_file = fopen(fname, mode);
228 if (opts.debug_file == NULL) {
229 fprintf(stderr, "Cannot open debug file \"%s\"\n",
237 MainParseArgDebug(const char *argvalue)
240 DebugFlags debug = opts.debug;
242 for (modules = argvalue; *modules != '\0'; modules++) {
244 case '0': /* undocumented, only intended for tests */
245 memset(&debug, 0, sizeof(debug));
248 memset(&debug, ~0, sizeof(debug));
251 debug.DEBUG_ARCH = true;
254 debug.DEBUG_CWD = true;
257 debug.DEBUG_COND = true;
260 debug.DEBUG_DIR = true;
263 debug.DEBUG_ERROR = true;
266 debug.DEBUG_FOR = true;
269 if (modules[1] == '1') {
270 debug.DEBUG_GRAPH1 = true;
272 } else if (modules[1] == '2') {
273 debug.DEBUG_GRAPH2 = true;
275 } else if (modules[1] == '3') {
276 debug.DEBUG_GRAPH3 = true;
281 debug.DEBUG_HASH = true;
284 debug.DEBUG_JOB = true;
290 debug.DEBUG_LOUD = true;
293 debug.DEBUG_META = true;
296 debug.DEBUG_MAKE = true;
299 debug.DEBUG_SCRIPT = true;
302 debug.DEBUG_PARSE = true;
305 debug.DEBUG_SUFF = true;
308 debug.DEBUG_TARG = true;
311 opts.debugVflag = true;
314 debug.DEBUG_VAR = true;
317 debug.DEBUG_SHELL = true;
320 MainParseArgDebugFile(modules + 1);
323 (void)fprintf(stderr,
324 "%s: illegal argument to d option -- %c\n",
333 setvbuf(opts.debug_file, NULL, _IONBF, 0);
334 if (opts.debug_file != stdout)
335 setvbuf(stdout, NULL, _IOLBF, 0);
338 /* Is path relative or does it contain any relative component "." or ".."? */
340 IsRelativePath(const char *path)
347 while ((p = strstr(p, "/.")) != NULL) {
351 if (*p == '/' || *p == '\0')
358 MainParseArgChdir(const char *argvalue)
362 if (chdir(argvalue) == -1) {
363 (void)fprintf(stderr, "%s: chdir %s: %s\n",
364 progname, argvalue, strerror(errno));
365 exit(2); /* Not 1 so -q can distinguish error */
367 if (getcwd(curdir, MAXPATHLEN) == NULL) {
368 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
371 if (!IsRelativePath(argvalue) &&
372 stat(argvalue, &sa) != -1 &&
373 stat(curdir, &sb) != -1 &&
374 sa.st_ino == sb.st_ino &&
375 sa.st_dev == sb.st_dev)
376 strncpy(curdir, argvalue, MAXPATHLEN);
381 MainParseArgJobsInternal(const char *argvalue)
384 if (sscanf(argvalue, "%d,%d%c", &jp_0, &jp_1, &end) != 2) {
385 (void)fprintf(stderr,
386 "%s: internal error -- J option malformed (%s)\n",
390 if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
391 (fcntl(jp_1, F_GETFD, 0) < 0)) {
394 opts.compatMake = true;
396 Global_Append(MAKEFLAGS, "-J");
397 Global_Append(MAKEFLAGS, argvalue);
402 MainParseArgJobs(const char *argvalue)
407 opts.maxJobs = (int)strtol(argvalue, &p, 0);
408 if (*p != '\0' || opts.maxJobs < 1) {
409 (void)fprintf(stderr,
410 "%s: illegal argument to -j -- must be positive integer!\n",
412 exit(2); /* Not 1 so -q can distinguish error */
414 Global_Append(MAKEFLAGS, "-j");
415 Global_Append(MAKEFLAGS, argvalue);
416 Global_Set(".MAKE.JOBS", argvalue);
417 maxJobTokens = opts.maxJobs;
421 MainParseArgSysInc(const char *argvalue)
423 /* look for magic parent directory search string */
424 if (strncmp(".../", argvalue, 4) == 0) {
425 char *found_path = Dir_FindHereOrAbove(curdir, argvalue + 4);
426 if (found_path == NULL)
428 (void)SearchPath_Add(sysIncPath, found_path);
431 (void)SearchPath_Add(sysIncPath, argvalue);
433 Global_Append(MAKEFLAGS, "-m");
434 Global_Append(MAKEFLAGS, argvalue);
438 MainParseArg(char c, const char *argvalue)
444 opts.compatMake = true;
445 Global_Append(MAKEFLAGS, "-B");
446 Global_Set(MAKE_MODE, "compat");
449 MainParseArgChdir(argvalue);
452 if (argvalue[0] == '\0')
454 Var_SetExpand(SCOPE_GLOBAL, argvalue, "1");
455 Global_Append(MAKEFLAGS, "-D");
456 Global_Append(MAKEFLAGS, argvalue);
459 Parse_AddIncludeDir(argvalue);
460 Global_Append(MAKEFLAGS, "-I");
461 Global_Append(MAKEFLAGS, argvalue);
464 MainParseArgJobsInternal(argvalue);
467 opts.noExecute = true;
468 opts.noRecursiveExecute = true;
469 Global_Append(MAKEFLAGS, "-N");
472 opts.keepgoing = false;
473 Global_Append(MAKEFLAGS, "-S");
476 tracefile = bmake_strdup(argvalue);
477 Global_Append(MAKEFLAGS, "-T");
478 Global_Append(MAKEFLAGS, argvalue);
482 opts.printVars = c == 'v' ? PVM_EXPANDED : PVM_UNEXPANDED;
483 Lst_Append(&opts.variables, bmake_strdup(argvalue));
484 /* XXX: Why always -V? */
485 Global_Append(MAKEFLAGS, "-V");
486 Global_Append(MAKEFLAGS, argvalue);
489 opts.parseWarnFatal = true;
490 /* XXX: why no Global_Append? */
493 opts.varNoExportEnv = true;
494 Global_Append(MAKEFLAGS, "-X");
497 /* If '-d-opts' don't pass to children */
498 if (argvalue[0] == '-')
501 Global_Append(MAKEFLAGS, "-d");
502 Global_Append(MAKEFLAGS, argvalue);
504 MainParseArgDebug(argvalue);
507 opts.checkEnvFirst = true;
508 Global_Append(MAKEFLAGS, "-e");
511 Lst_Append(&opts.makefiles, bmake_strdup(argvalue));
514 opts.ignoreErrors = true;
515 Global_Append(MAKEFLAGS, "-i");
518 MainParseArgJobs(argvalue);
521 opts.keepgoing = true;
522 Global_Append(MAKEFLAGS, "-k");
525 MainParseArgSysInc(argvalue);
526 /* XXX: why no Var_Append? */
529 opts.noExecute = true;
530 Global_Append(MAKEFLAGS, "-n");
534 /* Kind of nonsensical, wot? */
535 Global_Append(MAKEFLAGS, "-q");
538 opts.noBuiltins = true;
539 Global_Append(MAKEFLAGS, "-r");
543 Global_Append(MAKEFLAGS, "-s");
547 Global_Append(MAKEFLAGS, "-t");
550 opts.enterFlag = true;
551 Global_Append(MAKEFLAGS, "-w");
560 * Parse the given arguments. Called from main() and from
561 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
563 * The arguments must be treated as read-only and will be freed after the
566 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
569 MainParseArgs(int argc, char **argv)
575 bool inOption, dashDash = false;
577 const char *optspecs = "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrstv:w";
578 /* Can't actually use getopt(3) because rescanning is not portable */
597 if (c != '-' || dashDash)
602 /* '-' found at some earlier point */
603 optspec = strchr(optspecs, c);
604 if (c != '\0' && optspec != NULL && optspec[1] == ':') {
606 * -<something> found, and <something> should have an
612 if (*argvalue == '\0') {
630 if (!MainParseArg(c, argvalue))
638 * See if the rest of the arguments are variable assignments and
639 * perform them if so. Else take them to be targets and stuff them
640 * on the end of the "create" list.
642 for (; argc > 1; argv++, argc--) {
643 if (!Parse_VarAssign(argv[1], false, SCOPE_CMDLINE)) {
644 if (argv[1][0] == '\0')
645 Punt("illegal (null) argument.");
646 if (argv[1][0] == '-' && !dashDash)
648 Lst_Append(&opts.create, bmake_strdup(argv[1]));
654 (void)fprintf(stderr, "%s: option requires an argument -- %c\n",
660 * Break a line of arguments into words and parse them.
662 * Used when a .MFLAGS or .MAKEFLAGS target is encountered during parsing and
663 * by main() when reading the MAKEFLAGS environment variable.
666 Main_ParseArgLine(const char *line)
673 /* XXX: don't use line as an iterator variable */
674 for (; *line == ' '; line++)
682 * $MAKE may simply be naming the make(1) binary
686 if (!(cp = strrchr(line, '/')))
688 if ((cp = strstr(cp, "make")) &&
689 strcmp(cp, "make") == 0)
694 FStr argv0 = Var_Value(SCOPE_GLOBAL, ".MAKE");
695 buf = str_concat3(argv0.str, " ", line);
699 words = Str_Words(buf, true);
700 if (words.words == NULL) {
701 Error("Unterminated quoted string [%s]", buf);
706 MainParseArgs((int)words.len, words.words);
712 Main_SetObjdir(bool writable, const char *fmt, ...)
716 char buf[MAXPATHLEN + 1];
717 char buf2[MAXPATHLEN + 1];
721 vsnprintf(path = buf, MAXPATHLEN, fmt, ap);
724 if (path[0] != '/') {
725 snprintf(buf2, MAXPATHLEN, "%s/%s", curdir, path);
729 /* look for the directory and try to chdir there */
730 if (stat(path, &sb) != 0 || !S_ISDIR(sb.st_mode))
733 if ((writable && access(path, W_OK) != 0) || chdir(path) != 0) {
734 (void)fprintf(stderr, "%s: warning: %s: %s.\n",
735 progname, path, strerror(errno));
739 snprintf(objdir, sizeof objdir, "%s", path);
740 Global_Set(".OBJDIR", objdir);
741 setenv("PWD", objdir, 1);
743 purge_relative_cached_realpaths();
744 if (opts.enterFlag && strcmp(objdir, curdir) != 0)
750 SetVarObjdir(bool writable, const char *var, const char *suffix)
752 FStr path = Var_Value(SCOPE_CMDLINE, var);
754 if (path.str == NULL || path.str[0] == '\0') {
759 Var_Expand(&path, SCOPE_GLOBAL, VARE_WANTRES);
761 (void)Main_SetObjdir(writable, "%s%s", path.str, suffix);
768 * Splits str into words, adding them to the list.
769 * The string must be kept alive as long as the list.
772 str2Lst_Append(StringList *lp, char *str)
777 const char *sep = " \t";
779 for (n = 0, cp = strtok(str, sep); cp != NULL; cp = strtok(NULL, sep)) {
789 siginfo(int signo MAKE_ATTR_UNUSED)
791 char dir[MAXPATHLEN];
792 char str[2 * MAXPATHLEN];
794 if (getcwd(dir, sizeof dir) == NULL)
796 len = snprintf(str, sizeof str, "%s: Working in: %s\n", progname, dir);
798 (void)write(STDERR_FILENO, str, (size_t)len);
802 /* Allow makefiles some control over the mode we run in. */
808 (void)Var_Subst("${" MAKE_MODE ":tl}", SCOPE_GLOBAL, VARE_WANTRES, &mode);
809 /* TODO: handle errors */
811 if (mode[0] != '\0') {
812 if (strstr(mode, "compat") != NULL) {
813 opts.compatMake = true;
817 if (strstr(mode, "meta") != NULL)
818 meta_mode_init(mode);
820 if (strstr(mode, "randomize-targets") != NULL)
821 opts.randomizeTargets = true;
828 PrintVar(const char *varname, bool expandVars)
830 if (strchr(varname, '$') != NULL) {
832 (void)Var_Subst(varname, SCOPE_GLOBAL, VARE_WANTRES, &evalue);
833 /* TODO: handle errors */
834 printf("%s\n", evalue);
837 } else if (expandVars) {
838 char *expr = str_concat3("${", varname, "}");
840 (void)Var_Subst(expr, SCOPE_GLOBAL, VARE_WANTRES, &evalue);
841 /* TODO: handle errors */
843 printf("%s\n", evalue);
847 FStr value = Var_Value(SCOPE_GLOBAL, varname);
848 printf("%s\n", value.str != NULL ? value.str : "");
854 * Return a bool based on a variable.
856 * If the knob is not set, return the fallback.
857 * If set, anything that looks or smells like "No", "False", "Off", "0", etc.
858 * is false, otherwise true.
861 GetBooleanExpr(const char *expr, bool fallback)
866 (void)Var_Subst(expr, SCOPE_GLOBAL, VARE_WANTRES, &value);
867 /* TODO: handle errors */
868 res = ParseBoolean(value, fallback);
879 if (opts.printVars == PVM_EXPANDED)
881 else if (opts.debugVflag)
884 expandVars = GetBooleanExpr("${.MAKE.EXPAND_VARIABLES}",
887 for (ln = opts.variables.first; ln != NULL; ln = ln->next) {
888 const char *varname = ln->datum;
889 PrintVar(varname, expandVars);
896 GNodeList targs = LST_INIT; /* target nodes to create */
897 bool outOfDate; /* false if all targets up to date */
900 * Have now read the entire graph and need to make a list of
901 * targets to create. If none was given on the command line,
902 * we consult the parsing module to find the main target(s)
905 if (Lst_IsEmpty(&opts.create))
906 Parse_MainName(&targs);
908 Targ_FindList(&targs, &opts.create);
910 if (!opts.compatMake) {
912 * Initialize job module before traversing the graph
913 * now that any .BEGIN and .END targets have been read.
914 * This is done only if the -q flag wasn't given
915 * (to prevent the .BEGIN from being executed should
923 /* Traverse the graph, checking on all the targets */
924 outOfDate = Make_Run(&targs);
926 Compat_MakeAll(&targs);
929 Lst_Done(&targs); /* Don't free the targets themselves. */
934 * Set up the .TARGETS variable to contain the list of targets to be created.
935 * If none specified, make the variable empty for now, the parser will fill
936 * in the default or .MAIN target later.
943 if (Lst_IsEmpty(&opts.create)) {
944 Global_Set(".TARGETS", "");
948 for (ln = opts.create.first; ln != NULL; ln = ln->next) {
949 const char *name = ln->datum;
950 Global_Append(".TARGETS", name);
959 gettimeofday(&tv, NULL);
960 srandom((unsigned int)(tv.tv_sec + tv.tv_usec));
964 InitVarMachine(const struct utsname *utsname MAKE_ATTR_UNUSED)
967 return FORCE_MACHINE;
969 const char *machine = getenv("MACHINE");
974 #if defined(MAKE_NATIVE)
975 return utsname->machine;
976 #elif defined(MAKE_MACHINE)
985 InitVarMachineArch(void)
987 #ifdef FORCE_MACHINE_ARCH
988 return FORCE_MACHINE_ARCH;
990 const char *env = getenv("MACHINE_ARCH");
994 #if defined(MAKE_NATIVE) && defined(CTL_HW)
996 struct utsname utsname;
997 static char machine_arch_buf[sizeof utsname.machine];
998 const int mib[2] = { CTL_HW, HW_MACHINE_ARCH };
999 size_t len = sizeof machine_arch_buf;
1001 if (sysctl(mib, (unsigned int)__arraycount(mib),
1002 machine_arch_buf, &len, NULL, 0) < 0) {
1003 (void)fprintf(stderr, "%s: sysctl failed (%s).\n",
1004 progname, strerror(errno));
1008 return machine_arch_buf;
1010 #elif defined(MACHINE_ARCH)
1011 return MACHINE_ARCH;
1012 #elif defined(MAKE_MACHINE_ARCH)
1013 return MAKE_MACHINE_ARCH;
1020 #ifndef NO_PWD_OVERRIDE
1022 * All this code is so that we know where we are when we start up
1023 * on a different machine with pmake.
1025 * XXX: Make no longer has "local" and "remote" mode. Is this code still
1028 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
1029 * since the value of curdir can vary depending on how we got
1030 * here. Ie sitting at a shell prompt (shell that provides $PWD)
1031 * or via subdir.mk in which case its likely a shell which does
1034 * So, to stop it breaking this case only, we ignore PWD if
1035 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a variable expression.
1038 HandlePWD(const struct stat *curdir_st)
1044 if (ignorePWD || (pwd = getenv("PWD")) == NULL)
1047 if (Var_Exists(SCOPE_CMDLINE, "MAKEOBJDIRPREFIX"))
1050 makeobjdir = Var_Value(SCOPE_CMDLINE, "MAKEOBJDIR");
1051 if (makeobjdir.str != NULL && strchr(makeobjdir.str, '$') != NULL)
1054 if (stat(pwd, &pwd_st) == 0 &&
1055 curdir_st->st_ino == pwd_st.st_ino &&
1056 curdir_st->st_dev == pwd_st.st_dev)
1057 (void)strncpy(curdir, pwd, MAXPATHLEN);
1060 FStr_Done(&makeobjdir);
1065 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that, MAKEOBJDIR is set
1066 * in the environment, try only that value and fall back to .CURDIR if it
1069 * Otherwise, try _PATH_OBJDIR.MACHINE-MACHINE_ARCH, _PATH_OBJDIR.MACHINE,
1070 * and finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none of these
1071 * paths exist, just use .CURDIR.
1074 InitObjdir(const char *machine, const char *machine_arch)
1078 Dir_InitCur(curdir);
1079 writable = GetBooleanExpr("${MAKE_OBJDIR_CHECK_WRITABLE}", true);
1080 (void)Main_SetObjdir(false, "%s", curdir);
1082 if (!SetVarObjdir(writable, "MAKEOBJDIRPREFIX", curdir) &&
1083 !SetVarObjdir(writable, "MAKEOBJDIR", "") &&
1084 !Main_SetObjdir(writable, "%s.%s-%s", _PATH_OBJDIR, machine, machine_arch) &&
1085 !Main_SetObjdir(writable, "%s.%s", _PATH_OBJDIR, machine) &&
1086 !Main_SetObjdir(writable, "%s", _PATH_OBJDIR))
1087 (void)Main_SetObjdir(writable, "%s%s", _PATH_OBJDIRPREFIX, curdir);
1090 /* get rid of resource limit on file descriptors */
1094 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
1096 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
1097 rl.rlim_cur != rl.rlim_max) {
1098 rl.rlim_cur = rl.rlim_max;
1099 (void)setrlimit(RLIMIT_NOFILE, &rl);
1107 opts.compatMake = false;
1108 memset(&opts.debug, 0, sizeof(opts.debug));
1109 /* opts.debug_file has already been initialized earlier */
1110 opts.strict = false;
1111 opts.debugVflag = false;
1112 opts.checkEnvFirst = false;
1113 Lst_Init(&opts.makefiles);
1114 opts.ignoreErrors = false; /* Pay attention to non-zero returns */
1116 opts.keepgoing = false; /* Stop on error */
1117 opts.noRecursiveExecute = false; /* Execute all .MAKE targets */
1118 opts.noExecute = false; /* Execute all commands */
1120 opts.noBuiltins = false; /* Read the built-in rules */
1121 opts.silent = false; /* Print commands as executed */
1123 opts.printVars = PVM_NONE;
1124 Lst_Init(&opts.variables);
1125 opts.parseWarnFatal = false;
1126 opts.enterFlag = false;
1127 opts.varNoExportEnv = false;
1128 Lst_Init(&opts.create);
1132 * Initialize MAKE and .MAKE to the path of the executable, so that it can be
1133 * found by execvp(3) and the shells, even after a chdir.
1135 * If it's a relative path and contains a '/', resolve it to an absolute path.
1136 * Otherwise keep it as is, assuming it will be found in the PATH.
1139 InitVarMake(const char *argv0)
1141 const char *make = argv0;
1143 if (argv0[0] != '/' && strchr(argv0, '/') != NULL) {
1144 char pathbuf[MAXPATHLEN];
1145 const char *abspath = cached_realpath(argv0, pathbuf);
1147 if (abspath != NULL && abspath[0] == '/' &&
1148 stat(make, &st) == 0)
1152 Global_Set("MAKE", make);
1153 Global_Set(".MAKE", make);
1157 * Add the directories from the colon-separated syspath to defSysIncPath.
1158 * After returning, the contents of syspath is unspecified.
1161 InitDefSysIncPath(char *syspath)
1163 static char defsyspath[] = _PATH_DEFSYSPATH;
1167 * If no user-supplied system path was given (through the -m option)
1168 * add the directories from the DEFSYSPATH (more than one may be given
1169 * as dir1:...:dirn) to the system include path.
1171 if (syspath == NULL || syspath[0] == '\0')
1172 syspath = defsyspath;
1174 syspath = bmake_strdup(syspath);
1176 for (start = syspath; *start != '\0'; start = cp) {
1177 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1182 /* look for magic parent directory search string */
1183 if (strncmp(start, ".../", 4) == 0) {
1184 char *dir = Dir_FindHereOrAbove(curdir, start + 4);
1186 (void)SearchPath_Add(defSysIncPath, dir);
1190 (void)SearchPath_Add(defSysIncPath, start);
1194 if (syspath != defsyspath)
1199 ReadBuiltinRules(void)
1202 StringList sysMkFiles = LST_INIT;
1205 Lst_IsEmpty(&sysIncPath->dirs) ? defSysIncPath : sysIncPath,
1208 if (Lst_IsEmpty(&sysMkFiles))
1209 Fatal("%s: no system rules (%s).", progname, _PATH_DEFSYSMK);
1211 for (ln = sysMkFiles.first; ln != NULL; ln = ln->next)
1212 if (ReadMakefile(ln->datum))
1216 Fatal("%s: cannot open %s.",
1217 progname, (const char *)sysMkFiles.first->datum);
1219 Lst_DoneCall(&sysMkFiles, free);
1228 if (forceJobs || opts.compatMake ||
1229 !Var_Exists(SCOPE_GLOBAL, ".MAKE.JOBS"))
1232 (void)Var_Subst("${.MAKE.JOBS}", SCOPE_GLOBAL, VARE_WANTRES, &value);
1233 /* TODO: handle errors */
1234 n = (int)strtol(value, NULL, 0);
1236 (void)fprintf(stderr,
1237 "%s: illegal value for .MAKE.JOBS "
1238 "-- must be positive integer!\n",
1240 exit(2); /* Not 1 so -q can distinguish error */
1243 if (n != opts.maxJobs) {
1244 Global_Append(MAKEFLAGS, "-j");
1245 Global_Append(MAKEFLAGS, value);
1249 maxJobTokens = opts.maxJobs;
1255 * For compatibility, look at the directories in the VPATH variable
1256 * and add them to the search path, if the variable is defined. The
1257 * variable's value is in the same format as the PATH environment
1258 * variable, i.e. <directory>:<directory>:<directory>...
1263 char *vpath, savec, *path;
1264 if (!Var_Exists(SCOPE_CMDLINE, "VPATH"))
1267 (void)Var_Subst("${VPATH}", SCOPE_CMDLINE, VARE_WANTRES, &vpath);
1268 /* TODO: handle errors */
1272 /* skip to end of directory */
1273 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1275 /* Save terminator character so know when to stop */
1278 /* Add directory to search path */
1279 (void)SearchPath_Add(&dirSearchPath, path);
1282 } while (savec == ':');
1287 ReadAllMakefiles(const StringList *makefiles)
1291 for (ln = makefiles->first; ln != NULL; ln = ln->next) {
1292 const char *fname = ln->datum;
1293 if (!ReadMakefile(fname))
1294 Fatal("%s: cannot open %s.", progname, fname);
1299 ReadFirstDefaultMakefile(void)
1301 StringList makefiles = LST_INIT;
1305 (void)Var_Subst("${" MAKE_MAKEFILE_PREFERENCE "}",
1306 SCOPE_CMDLINE, VARE_WANTRES, &prefs);
1307 /* TODO: handle errors */
1309 (void)str2Lst_Append(&makefiles, prefs);
1311 for (ln = makefiles.first; ln != NULL; ln = ln->next)
1312 if (ReadMakefile(ln->datum))
1315 Lst_Done(&makefiles);
1320 * Initialize variables such as MAKE, MACHINE, .MAKEFLAGS.
1321 * Initialize a few modules.
1322 * Parse the arguments from MAKEFLAGS and the command line.
1325 main_Init(int argc, char **argv)
1328 const char *machine;
1329 const char *machine_arch;
1330 char *syspath = getenv("MAKESYSPATH");
1331 struct utsname utsname;
1333 /* default to writing debug to stderr */
1334 opts.debug_file = stderr;
1337 HashTable_Init(&cached_realpaths);
1340 (void)bmake_signal(SIGINFO, siginfo);
1345 progname = str_basename(argv[0]);
1349 if (uname(&utsname) == -1) {
1350 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
1356 * Get the name of this type of MACHINE from utsname
1357 * so we can share an executable for similar machines.
1358 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
1360 * Note that both MACHINE and MACHINE_ARCH are decided at
1363 machine = InitVarMachine(&utsname);
1364 machine_arch = InitVarMachineArch();
1366 myPid = getpid(); /* remember this for vFork() */
1369 * Just in case MAKEOBJDIR wants us to do something tricky.
1373 Global_Set(".MAKE.OS", utsname.sysname);
1374 Global_Set("MACHINE", machine);
1375 Global_Set("MACHINE_ARCH", machine_arch);
1377 Global_Set("MAKE_VERSION", MAKE_VERSION);
1379 Global_Set(".newline", "\n"); /* handy for :@ loops */
1380 #ifndef MAKEFILE_PREFERENCE_LIST
1381 /* This is the traditional preference for makefiles. */
1382 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
1384 Global_Set(MAKE_MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST);
1385 Global_Set(MAKE_DEPENDFILE, ".depend");
1388 allPrecious = false; /* Remove targets when interrupted */
1389 deleteOnError = false; /* Historical default behavior */
1390 jobsRunning = false;
1392 maxJobTokens = opts.maxJobs;
1396 * Initialize the parsing, directory and variable modules to prepare
1397 * for the reading of inclusion paths and variable settings on the
1402 * Initialize various variables.
1403 * MAKE also gets this name, for compatibility
1404 * .MAKEFLAGS gets set to the empty string just in case.
1405 * MFLAGS also gets initialized empty, for compatibility.
1408 InitVarMake(argv[0]);
1409 Global_Set(MAKEFLAGS, "");
1410 Global_Set(MAKEOVERRIDES, "");
1411 Global_Set("MFLAGS", "");
1412 Global_Set(".ALLTARGETS", "");
1413 Var_Set(SCOPE_CMDLINE, MAKE_LEVEL ".ENV", MAKE_LEVEL_ENV);
1415 /* Set some other useful variables. */
1417 char buf[64], *ep = getenv(MAKE_LEVEL_ENV);
1419 makelevel = ep != NULL && ep[0] != '\0' ? atoi(ep) : 0;
1422 snprintf(buf, sizeof buf, "%d", makelevel);
1423 Global_Set(MAKE_LEVEL, buf);
1424 snprintf(buf, sizeof buf, "%u", myPid);
1425 Global_Set(".MAKE.PID", buf);
1426 snprintf(buf, sizeof buf, "%u", getppid());
1427 Global_Set(".MAKE.PPID", buf);
1428 snprintf(buf, sizeof buf, "%u", getuid());
1429 Global_Set(".MAKE.UID", buf);
1430 snprintf(buf, sizeof buf, "%u", getgid());
1431 Global_Set(".MAKE.GID", buf);
1433 if (makelevel > 0) {
1435 snprintf(pn, sizeof pn, "%s[%d]", progname, makelevel);
1436 progname = bmake_strdup(pn);
1446 char *makeflags = explode(getenv("MAKEFLAGS"));
1447 Main_ParseArgLine(makeflags);
1452 * First snag any flags out of the MAKE environment variable.
1453 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
1454 * in a different format).
1456 Main_ParseArgLine(getenv("MAKE"));
1459 if (getcwd(curdir, MAXPATHLEN) == NULL) {
1460 (void)fprintf(stderr, "%s: getcwd: %s.\n",
1461 progname, strerror(errno));
1465 MainParseArgs(argc, argv);
1468 printf("%s: Entering directory `%s'\n", progname, curdir);
1470 if (stat(curdir, &sa) == -1) {
1471 (void)fprintf(stderr, "%s: %s: %s.\n",
1472 progname, curdir, strerror(errno));
1476 #ifndef NO_PWD_OVERRIDE
1479 Global_Set(".CURDIR", curdir);
1481 InitObjdir(machine, machine_arch);
1485 Trace_Init(tracefile);
1490 Trace_Log(MAKESTART, NULL);
1494 InitDefSysIncPath(syspath);
1498 * Read the system makefile followed by either makefile, Makefile or the
1499 * files given by the -f option. Exit on parse errors.
1502 main_ReadFiles(void)
1505 if (!opts.noBuiltins)
1508 posix_state = PS_MAYBE_NEXT_LINE;
1509 if (!Lst_IsEmpty(&opts.makefiles))
1510 ReadAllMakefiles(&opts.makefiles);
1512 ReadFirstDefaultMakefile();
1515 /* Compute the dependency graph. */
1517 main_PrepareMaking(void)
1519 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1520 if (!opts.noBuiltins || opts.printVars == PVM_NONE) {
1521 (void)Var_Subst("${.MAKE.DEPENDFILE}",
1522 SCOPE_CMDLINE, VARE_WANTRES, &makeDependfile);
1523 if (makeDependfile[0] != '\0') {
1524 /* TODO: handle errors */
1525 doing_depend = true;
1526 (void)ReadMakefile(makeDependfile);
1527 doing_depend = false;
1532 printf("%s: Entering directory `%s'\n", progname, objdir);
1537 FStr makeflags = Var_Value(SCOPE_GLOBAL, MAKEFLAGS);
1538 Global_Append("MFLAGS", makeflags.str);
1539 FStr_Done(&makeflags);
1544 if (!opts.compatMake && !forceJobs)
1545 opts.compatMake = true;
1547 if (!opts.compatMake)
1548 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1549 DEBUG5(JOB, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1550 jp_0, jp_1, opts.maxJobs, maxJobTokens, opts.compatMake ? 1 : 0);
1552 if (opts.printVars == PVM_NONE)
1553 Main_ExportMAKEFLAGS(true); /* initial export */
1558 * Now that all search paths have been read for suffixes et al, it's
1559 * time to add the default search path to their lists...
1564 * Propagate attributes through :: dependency lists.
1568 /* print the initial graph, if the user requested it */
1575 * If the -v or -V options are given, print variables instead.
1576 * Return whether any of the targets is out-of-date.
1581 if (opts.printVars != PVM_NONE) {
1582 /* print the values of any variables requested by the user */
1586 return runTargets();
1590 /* Clean up after making the targets. */
1595 Lst_DoneCall(&opts.variables, free);
1596 Lst_DoneCall(&opts.makefiles, free);
1597 Lst_DoneCall(&opts.create, free);
1603 Trace_Log(MAKEEND, NULL);
1606 printf("%s: Leaving directory `%s'\n", progname, objdir);
1608 printf("%s: Leaving directory `%s'\n", progname, curdir);
1624 /* Determine the exit code. */
1626 main_Exit(bool outOfDate)
1628 if (opts.strict && (main_errors > 0 || Parse_NumErrors() > 0))
1629 return 2; /* Not 1 so -q can distinguish error */
1630 return outOfDate ? 1 : 0;
1634 main(int argc, char **argv)
1638 main_Init(argc, argv);
1640 main_PrepareMaking();
1641 outOfDate = main_Run();
1643 return main_Exit(outOfDate);
1647 * Open and parse the given makefile, with all its side effects.
1648 * Return false if the file could not be opened.
1651 ReadMakefile(const char *fname)
1654 char *name, *path = NULL;
1656 if (strcmp(fname, "-") == 0) {
1657 Parse_File("(stdin)", -1);
1658 Var_Set(SCOPE_INTERNAL, "MAKEFILE", "");
1660 /* if we've chdir'd, rebuild the path name */
1661 if (strcmp(curdir, objdir) != 0 && *fname != '/') {
1662 path = str_concat3(curdir, "/", fname);
1663 fd = open(path, O_RDONLY);
1670 /* If curdir failed, try objdir (ala .depend) */
1671 path = str_concat3(objdir, "/", fname);
1672 fd = open(path, O_RDONLY);
1678 fd = open(fname, O_RDONLY);
1682 /* look in -I and system include directories. */
1683 name = Dir_FindFile(fname, parseIncPath);
1685 SearchPath *sysInc = Lst_IsEmpty(&sysIncPath->dirs)
1686 ? defSysIncPath : sysIncPath;
1687 name = Dir_FindFile(fname, sysInc);
1689 if (name == NULL || (fd = open(name, O_RDONLY)) == -1) {
1696 * set the MAKEFILE variable desired by System V fans -- the
1697 * placement of the setting here means it gets set to the last
1698 * makefile specified, as it is set by SysV make.
1702 Var_Set(SCOPE_INTERNAL, "MAKEFILE", fname);
1703 Parse_File(fname, fd);
1710 * Execute the command in cmd, and return its output (only stdout, not
1711 * stderr, possibly empty). In the output, replace newlines with spaces.
1714 Cmd_Exec(const char *cmd, char **error)
1716 const char *args[4]; /* Arguments for invoking the shell */
1718 int cpid; /* Child PID */
1719 int pid; /* PID from wait() */
1720 int status; /* command exit status */
1721 Buffer buf; /* buffer to store the result */
1727 if (shellName == NULL)
1730 args[0] = shellName;
1734 DEBUG1(VAR, "Capturing the output of command \"%s\"\n", cmd);
1736 if (pipe(pipefds) == -1) {
1737 *error = str_concat3(
1738 "Couldn't create pipe for \"", cmd, "\"");
1739 return bmake_strdup("");
1744 switch (cpid = vfork()) {
1746 (void)close(pipefds[0]);
1747 (void)dup2(pipefds[1], STDOUT_FILENO);
1748 (void)close(pipefds[1]);
1750 (void)execv(shellPath, UNCONST(args));
1755 *error = str_concat3("Couldn't exec \"", cmd, "\"");
1756 return bmake_strdup("");
1759 (void)close(pipefds[1]); /* No need for the writing half */
1765 char result[BUFSIZ];
1766 bytes_read = read(pipefds[0], result, sizeof result);
1768 Buf_AddBytes(&buf, result, (size_t)bytes_read);
1769 } while (bytes_read > 0 || (bytes_read == -1 && errno == EINTR));
1770 if (bytes_read == -1)
1771 saved_errno = errno;
1773 (void)close(pipefds[0]); /* Close the input side of the pipe. */
1775 while ((pid = waitpid(cpid, &status, 0)) != cpid && pid >= 0)
1776 JobReapChild(pid, status, false);
1778 if (Buf_EndsWith(&buf, '\n'))
1779 buf.data[buf.len - 1] = '\0';
1781 output = Buf_DoneData(&buf);
1782 for (cp = output; *cp != '\0'; cp++)
1786 if (WIFSIGNALED(status))
1787 *error = str_concat3("\"", cmd, "\" exited on a signal");
1788 else if (WEXITSTATUS(status) != 0)
1789 *error = str_concat3(
1790 "\"", cmd, "\" returned non-zero status");
1791 else if (saved_errno != 0)
1792 *error = str_concat3(
1793 "Couldn't read shell's output for \"", cmd, "\"");
1800 * Print a printf-style error message.
1802 * In default mode, this error message has no consequences, for compatibility
1803 * reasons, in particular it does not affect the exit status. Only in lint
1804 * mode (-dL) it does.
1807 Error(const char *fmt, ...)
1812 f = opts.debug_file;
1815 (void)fflush(stdout);
1818 fprintf(f, "%s: ", progname);
1820 (void)vfprintf(f, fmt, ap);
1822 (void)fprintf(f, "\n");
1832 * Wait for any running jobs to finish, then produce an error message,
1833 * finally exit immediately.
1835 * Exiting immediately differs from Parse_Error, which exits only after the
1836 * current top-level makefile has been parsed completely.
1839 Fatal(const char *fmt, ...)
1846 (void)fflush(stdout);
1848 (void)vfprintf(stderr, fmt, ap);
1850 (void)fprintf(stderr, "\n");
1851 (void)fflush(stderr);
1852 PrintStackTrace(true);
1854 PrintOnError(NULL, "\n");
1856 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1858 Trace_Log(MAKEERROR, NULL);
1859 exit(2); /* Not 1 so -q can distinguish error */
1863 * Major exception once jobs are being created.
1864 * Kills all jobs, prints a message and exits.
1867 Punt(const char *fmt, ...)
1871 (void)fflush(stdout);
1872 (void)fprintf(stderr, "%s: ", progname);
1874 (void)vfprintf(stderr, fmt, ap);
1876 (void)fprintf(stderr, "\n");
1877 (void)fflush(stderr);
1879 PrintOnError(NULL, "\n");
1884 /* Exit without giving a message. */
1892 Trace_Log(MAKEERROR, NULL);
1893 exit(2); /* Not 1 so -q can distinguish error */
1897 * Called when aborting due to errors in child shell to signal abnormal exit.
1898 * The program exits.
1899 * Errors is the number of errors encountered in Make_Make.
1904 if (shouldDieQuietly(NULL, -1))
1906 Fatal("%d error%s", errs, errs == 1 ? "" : "s");
1910 unlink_file(const char *file)
1914 if (lstat(file, &st) == -1)
1917 if (S_ISDIR(st.st_mode)) {
1921 return unlink(file) == 0;
1925 write_all(int fd, const void *data, size_t n)
1927 const char *mem = data;
1930 ssize_t written = write(fd, mem, n);
1931 /* XXX: Should this EAGAIN be EINTR? */
1932 if (written == -1 && errno == EAGAIN)
1937 n -= (size_t)written;
1941 /* Print why exec failed, avoiding stdio. */
1943 execDie(const char *af, const char *av)
1948 Buf_AddStr(&buf, progname);
1949 Buf_AddStr(&buf, ": ");
1950 Buf_AddStr(&buf, af);
1951 Buf_AddStr(&buf, "(");
1952 Buf_AddStr(&buf, av);
1953 Buf_AddStr(&buf, ") failed (");
1954 Buf_AddStr(&buf, strerror(errno));
1955 Buf_AddStr(&buf, ")\n");
1957 write_all(STDERR_FILENO, buf.data, buf.len);
1964 purge_relative_cached_realpaths(void)
1966 HashEntry *he, *nhe;
1969 HashIter_Init(&hi, &cached_realpaths);
1970 he = HashIter_Next(&hi);
1971 while (he != NULL) {
1972 nhe = HashIter_Next(&hi);
1973 if (he->key[0] != '/') {
1974 DEBUG1(DIR, "cached_realpath: purging %s\n", he->key);
1975 HashTable_DeleteEntry(&cached_realpaths, he);
1977 * XXX: What about the allocated he->value? Either
1978 * free them or document why they cannot be freed.
1986 cached_realpath(const char *pathname, char *resolved)
1990 if (pathname == NULL || pathname[0] == '\0')
1993 rp = HashTable_FindValue(&cached_realpaths, pathname);
1996 strncpy(resolved, rp, MAXPATHLEN);
1997 resolved[MAXPATHLEN - 1] = '\0';
2001 rp = realpath(pathname, resolved);
2003 HashTable_Set(&cached_realpaths, pathname, bmake_strdup(rp));
2004 DEBUG2(DIR, "cached_realpath: %s -> %s\n", pathname, rp);
2008 /* should we negative-cache? */
2013 * Return true if we should die without noise.
2014 * For example our failing child was a sub-make or failure happened elsewhere.
2017 shouldDieQuietly(GNode *gn, int bf)
2019 static int quietly = -1;
2023 !GetBooleanExpr("${.MAKE.DIE_QUIETLY}", true))
2028 quietly = (gn != NULL && (gn->type & OP_MAKE)) ? 1 : 0;
2030 return quietly != 0;
2034 SetErrorVars(GNode *gn)
2039 * We can print this even if there is no .ERROR target.
2041 Global_Set(".ERROR_TARGET", gn->name);
2042 Global_Delete(".ERROR_CMD");
2044 for (ln = gn->commands.first; ln != NULL; ln = ln->next) {
2045 const char *cmd = ln->datum;
2049 Global_Append(".ERROR_CMD", cmd);
2054 * Print some helpful information in case of an error.
2055 * The caller should exit soon after calling this function.
2058 PrintOnError(GNode *gn, const char *msg)
2060 static GNode *errorNode = NULL;
2067 if (errorNode != NULL)
2068 return; /* we've been here! */
2070 printf("%s%s: stopped in %s\n", msg, progname, curdir);
2072 /* we generally want to keep quiet if a sub-make died */
2073 if (shouldDieQuietly(gn, -1))
2080 char *errorVarsValues;
2081 (void)Var_Subst("${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
2082 SCOPE_GLOBAL, VARE_WANTRES, &errorVarsValues);
2083 /* TODO: handle errors */
2084 printf("%s", errorVarsValues);
2085 free(errorVarsValues);
2091 * Finally, see if there is a .ERROR target, and run it if so.
2093 errorNode = Targ_FindNode(".ERROR");
2094 if (errorNode != NULL) {
2095 errorNode->type |= OP_SPECIAL;
2096 Compat_Make(errorNode, errorNode);
2101 Main_ExportMAKEFLAGS(bool first)
2103 static bool once = true;
2111 "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
2112 SCOPE_CMDLINE, VARE_WANTRES, &flags);
2113 /* TODO: handle errors */
2114 if (flags[0] != '\0') {
2116 setenv("MAKEFLAGS", flags, 1);
2118 setenv("MAKE", flags, 1);
2126 static char *tmpdir = NULL;
2132 /* Honor $TMPDIR if it is valid, strip a trailing '/'. */
2133 (void)Var_Subst("${TMPDIR:tA:U" _PATH_TMP ":S,/$,,W}/",
2134 SCOPE_GLOBAL, VARE_WANTRES, &tmpdir);
2135 /* TODO: handle errors */
2137 if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
2139 tmpdir = bmake_strdup(_PATH_TMP);
2145 * Create and open a temp file using "pattern".
2146 * If out_fname is provided, set it to a copy of the filename created.
2147 * Otherwise unlink the file once open.
2150 mkTempFile(const char *pattern, char *tfile, size_t tfile_sz)
2152 static char *tmpdir = NULL;
2153 char tbuf[MAXPATHLEN];
2156 if (pattern == NULL)
2159 tmpdir = getTmpdir();
2160 if (tfile == NULL) {
2162 tfile_sz = sizeof tbuf;
2165 if (pattern[0] == '/')
2166 snprintf(tfile, tfile_sz, "%s", pattern);
2168 snprintf(tfile, tfile_sz, "%s%s", tmpdir, pattern);
2170 if ((fd = mkstemp(tfile)) < 0)
2171 Punt("Could not create temporary file %s: %s", tfile,
2174 unlink(tfile); /* we just want the descriptor */
2180 * Convert a string representation of a boolean into a boolean value.
2181 * Anything that looks like "No", "False", "Off", "0" etc. is false,
2182 * the empty string is the fallback, everything else is true.
2185 ParseBoolean(const char *s, bool fallback)
2187 char ch = ch_tolower(s[0]);
2190 if (ch == '0' || ch == 'f' || ch == 'n')
2193 return ch_tolower(s[1]) != 'f';