1 /* $NetBSD: main.c,v 1.421 2020/11/01 00:24:57 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
73 * The main file for this entire program. Exit routines etc
76 * Utility functions defined in this file:
77 * Main_ParseArgLine Takes a line of arguments, breaks them and
78 * treats them as if they were given when first
79 * invoked. Used by the parse module to implement
82 * Error Print a tagged error message. The global
83 * MAKE variable must have been defined. This
84 * takes a format string and optional arguments
87 * Fatal Print an error message and exit. Also takes
88 * a format string and arguments for it.
90 * Punt Aborts all jobs and exits with a message. Also
91 * takes a format string and arguments for it.
93 * Finish Finish things up by printing the number of
94 * errors which occurred, as passed to it, and
98 #include <sys/types.h>
100 #include <sys/param.h>
101 #include <sys/resource.h>
102 #include <sys/stat.h>
103 #if defined(MAKE_NATIVE) && defined(HAVE_SYSCTL)
104 #include <sys/sysctl.h>
106 #include <sys/utsname.h>
117 #include "pathnames.h"
120 /* "@(#)main.c 8.3 (Berkeley) 3/19/94" */
121 MAKE_RCSID("$NetBSD: main.c,v 1.421 2020/11/01 00:24:57 rillig Exp $");
122 #if defined(MAKE_NATIVE) && !defined(lint)
123 __COPYRIGHT("@(#) Copyright (c) 1988, 1989, 1990, 1993 "
124 "The Regents of the University of California. "
125 "All rights reserved.");
129 #define DEFMAXLOCAL DEFMAXJOBS
133 # define __arraycount(__x) (sizeof(__x) / sizeof(__x[0]))
137 time_t now; /* Time at start of make */
138 GNode *DEFAULT; /* .DEFAULT node */
139 Boolean allPrecious; /* .PRECIOUS given on line by itself */
140 Boolean deleteOnError; /* .DELETE_ON_ERROR: set */
142 static int maxJobTokens; /* -j argument */
143 Boolean enterFlagObj; /* -w and objdir != srcdir */
145 Boolean oldVars; /* variable substitution style */
146 static int jp_0 = -1, jp_1 = -1; /* ends of parent job pipe */
147 Boolean doing_depend; /* Set while reading .depend */
148 static Boolean jobsRunning; /* TRUE if the jobs might be running */
149 static const char * tracefile;
150 static int ReadMakefile(const char *);
151 static void usage(void) MAKE_ATTR_DEAD;
152 static void purge_cached_realpaths(void);
154 static Boolean ignorePWD; /* if we use -C, PWD is meaningless */
155 static char objdir[MAXPATHLEN + 1]; /* where we chdir'ed to */
156 char curdir[MAXPATHLEN + 1]; /* Startup directory */
157 char *progname; /* the program name */
158 char *makeDependfile;
162 Boolean forceJobs = FALSE;
163 static int errors = 0;
166 * On some systems MACHINE is defined as something other than
171 # define MACHINE FORCE_MACHINE
174 extern SearchPath *parseIncPath;
177 * For compatibility with the POSIX version of MAKEFLAGS that includes
178 * all the options with out -, convert flags to -f -l -a -g -s.
181 explode(const char *flags)
190 for (f = flags; *f; f++)
195 return bmake_strdup(flags);
198 st = nf = bmake_malloc(len * 3 + 1);
209 parse_debug_option_F(const char *modules)
215 if (opts.debug_file != stdout && opts.debug_file != stderr)
216 fclose(opts.debug_file);
218 if (*modules == '+') {
224 if (strcmp(modules, "stdout") == 0) {
225 opts.debug_file = stdout;
228 if (strcmp(modules, "stderr") == 0) {
229 opts.debug_file = stderr;
233 len = strlen(modules);
234 fname = bmake_malloc(len + 20);
235 memcpy(fname, modules, len + 1);
237 /* Let the filename be modified by the pid */
238 if (strcmp(fname + len - 3, ".%d") == 0)
239 snprintf(fname + len - 2, 20, "%d", getpid());
241 opts.debug_file = fopen(fname, mode);
242 if (!opts.debug_file) {
243 fprintf(stderr, "Cannot open debug file %s\n",
251 parse_debug_options(const char *argvalue)
255 for (modules = argvalue; *modules; ++modules) {
257 case '0': /* undocumented, only intended for tests */
258 opts.debug &= DEBUG_LINT;
261 opts.debug = ~(0|DEBUG_LINT);
264 opts.debug |= DEBUG_ARCH;
267 opts.debug |= DEBUG_CWD;
270 opts.debug |= DEBUG_COND;
273 opts.debug |= DEBUG_DIR;
276 opts.debug |= DEBUG_ERROR;
279 opts.debug |= DEBUG_FOR;
282 if (modules[1] == '1') {
283 opts.debug |= DEBUG_GRAPH1;
286 else if (modules[1] == '2') {
287 opts.debug |= DEBUG_GRAPH2;
290 else if (modules[1] == '3') {
291 opts.debug |= DEBUG_GRAPH3;
296 opts.debug |= DEBUG_HASH;
299 opts.debug |= DEBUG_JOB;
302 opts.debug |= DEBUG_LINT;
305 opts.debug |= DEBUG_LOUD;
308 opts.debug |= DEBUG_META;
311 opts.debug |= DEBUG_MAKE;
314 opts.debug |= DEBUG_SCRIPT;
317 opts.debug |= DEBUG_PARSE;
320 opts.debug |= DEBUG_SUFF;
323 opts.debug |= DEBUG_TARG;
326 opts.debugVflag = TRUE;
329 opts.debug |= DEBUG_VAR;
332 opts.debug |= DEBUG_SHELL;
335 parse_debug_option_F(modules + 1);
338 (void)fprintf(stderr,
339 "%s: illegal argument to d option -- %c\n",
346 * Make the debug_file unbuffered, and make
347 * stdout line buffered (unless debugfile == stdout).
349 setvbuf(opts.debug_file, NULL, _IONBF, 0);
350 if (opts.debug_file != stdout) {
351 setvbuf(stdout, NULL, _IOLBF, 0);
356 * does path contain any relative components
359 is_relpath(const char *path)
366 while ((cp = strstr(cp, "/.")) != NULL) {
368 if (cp[0] == '/' || cp[0] == '\0')
370 else if (cp[0] == '.') {
371 if (cp[1] == '/' || cp[1] == '\0')
379 MainParseArgChdir(const char *argvalue)
383 if (chdir(argvalue) == -1) {
384 (void)fprintf(stderr, "%s: chdir %s: %s\n",
385 progname, argvalue, strerror(errno));
388 if (getcwd(curdir, MAXPATHLEN) == NULL) {
389 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
392 if (!is_relpath(argvalue) &&
393 stat(argvalue, &sa) != -1 &&
394 stat(curdir, &sb) != -1 &&
395 sa.st_ino == sb.st_ino &&
396 sa.st_dev == sb.st_dev)
397 strncpy(curdir, argvalue, MAXPATHLEN);
402 MainParseArgJobsInternal(const char *argvalue)
404 if (sscanf(argvalue, "%d,%d", &jp_0, &jp_1) != 2) {
405 (void)fprintf(stderr,
406 "%s: internal error -- J option malformed (%s)\n",
410 if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
411 (fcntl(jp_1, F_GETFD, 0) < 0)) {
413 (void)fprintf(stderr,
414 "%s: ###### warning -- J descriptors were closed!\n",
420 opts.compatMake = TRUE;
422 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
423 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
428 MainParseArgJobs(const char *argvalue)
433 opts.maxJobs = (int)strtol(argvalue, &p, 0);
434 if (*p != '\0' || opts.maxJobs < 1) {
435 (void)fprintf(stderr,
436 "%s: illegal argument to -j -- must be positive integer!\n",
438 exit(1); /* XXX: why not 2? */
440 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
441 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
442 Var_Set(".MAKE.JOBS", argvalue, VAR_GLOBAL);
443 maxJobTokens = opts.maxJobs;
447 MainParseArgSysInc(const char *argvalue)
449 /* look for magic parent directory search string */
450 if (strncmp(".../", argvalue, 4) == 0) {
451 char *found_path = Dir_FindHereOrAbove(curdir, argvalue + 4);
452 if (found_path == NULL)
454 (void)Dir_AddDir(sysIncPath, found_path);
457 (void)Dir_AddDir(sysIncPath, argvalue);
459 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
460 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
464 MainParseArg(char c, const char *argvalue)
470 opts.compatMake = TRUE;
471 Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
472 Var_Set(MAKE_MODE, "compat", VAR_GLOBAL);
475 MainParseArgChdir(argvalue);
478 if (argvalue[0] == '\0') return FALSE;
479 Var_Set(argvalue, "1", VAR_GLOBAL);
480 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
481 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
484 Parse_AddIncludeDir(argvalue);
485 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
486 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
489 MainParseArgJobsInternal(argvalue);
492 opts.noExecute = TRUE;
493 opts.noRecursiveExecute = TRUE;
494 Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
497 opts.keepgoing = FALSE;
498 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
501 tracefile = bmake_strdup(argvalue);
502 Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
503 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
507 opts.printVars = c == 'v' ? EXPAND_VARS : COMPAT_VARS;
508 Lst_Append(opts.variables, bmake_strdup(argvalue));
509 /* XXX: Why always -V? */
510 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
511 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
514 opts.parseWarnFatal = TRUE;
517 opts.varNoExportEnv = TRUE;
518 Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
521 /* If '-d-opts' don't pass to children */
522 if (argvalue[0] == '-')
525 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
526 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
528 parse_debug_options(argvalue);
531 opts.checkEnvFirst = TRUE;
532 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
535 Lst_Append(opts.makefiles, bmake_strdup(argvalue));
538 opts.ignoreErrors = TRUE;
539 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
542 MainParseArgJobs(argvalue);
545 opts.keepgoing = TRUE;
546 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
549 MainParseArgSysInc(argvalue);
552 opts.noExecute = TRUE;
553 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
556 opts.queryFlag = TRUE;
557 /* Kind of nonsensical, wot? */
558 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
561 opts.noBuiltins = TRUE;
562 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
565 opts.beSilent = TRUE;
566 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
569 opts.touchFlag = TRUE;
570 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
573 opts.enterFlag = TRUE;
574 Var_Append(MAKEFLAGS, "-w", VAR_GLOBAL);
583 /* Parse the given arguments. Called from main() and from
584 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
586 * The arguments must be treated as read-only and will be freed after the
589 * XXX: Deal with command line overriding .MAKEFLAGS in makefile */
591 MainParseArgs(int argc, char **argv)
597 Boolean inOption, dashDash = FALSE;
599 const char *optspecs = "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrstv:w";
600 /* Can't actually use getopt(3) because rescanning is not portable */
619 if (c != '-' || dashDash)
624 /* '-' found at some earlier point */
625 optspec = strchr(optspecs, c);
626 if (c != '\0' && optspec != NULL && optspec[1] == ':') {
627 /* -<something> found, and <something> should have an arg */
631 if (*argvalue == '\0') {
649 if (!MainParseArg(c, argvalue))
659 * See if the rest of the arguments are variable assignments and
660 * perform them if so. Else take them to be targets and stuff them
661 * on the end of the "create" list.
663 for (; argc > 1; ++argv, --argc) {
665 if (Parse_IsVar(argv[1], &var)) {
666 Parse_DoVar(&var, VAR_CMDLINE);
669 Punt("illegal (null) argument.");
670 if (*argv[1] == '-' && !dashDash)
672 Lst_Append(opts.create, bmake_strdup(argv[1]));
678 (void)fprintf(stderr, "%s: option requires an argument -- %c\n",
683 /* Break a line of arguments into words and parse them.
685 * Used when a .MFLAGS or .MAKEFLAGS target is encountered during parsing and
686 * by main() when reading the MAKEFLAGS environment variable. */
688 Main_ParseArgLine(const char *line)
692 const char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
697 for (; *line == ' '; ++line)
705 * $MAKE may simply be naming the make(1) binary
709 if (!(cp = strrchr(line, '/')))
711 if ((cp = strstr(cp, "make")) &&
712 strcmp(cp, "make") == 0)
716 buf = str_concat3(argv0, " ", line);
719 words = Str_Words(buf, TRUE);
720 if (words.words == NULL) {
721 Error("Unterminated quoted string [%s]", buf);
726 MainParseArgs((int)words.len, words.words);
732 Main_SetObjdir(const char *fmt, ...)
736 char buf[MAXPATHLEN + 1];
737 char buf2[MAXPATHLEN + 1];
742 vsnprintf(path = buf, MAXPATHLEN, fmt, ap);
745 if (path[0] != '/') {
746 snprintf(buf2, MAXPATHLEN, "%s/%s", curdir, path);
750 /* look for the directory and try to chdir there */
751 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
752 /* if not .CURDIR it must be writable */
753 if ((strcmp(path, curdir) != 0 && access(path, W_OK) != 0) ||
755 (void)fprintf(stderr, "make warning: %s: %s.\n",
756 path, strerror(errno));
758 snprintf(objdir, sizeof objdir, "%s", path);
759 Var_Set(".OBJDIR", objdir, VAR_GLOBAL);
760 setenv("PWD", objdir, 1);
762 purge_cached_realpaths();
764 if (opts.enterFlag && strcmp(objdir, curdir) != 0)
773 Main_SetVarObjdir(const char *var, const char *suffix)
776 const char *path = Var_Value(var, VAR_CMDLINE, &path_freeIt);
780 if (path == NULL || path[0] == '\0') {
781 bmake_free(path_freeIt);
785 /* expand variable substitutions */
788 if (strchr(path, '$') != 0) {
789 (void)Var_Subst(path, VAR_GLOBAL, VARE_WANTRES, &xpath_freeIt);
790 /* TODO: handle errors */
791 xpath = xpath_freeIt;
794 (void)Main_SetObjdir("%s%s", xpath, suffix);
796 bmake_free(xpath_freeIt);
797 bmake_free(path_freeIt);
801 /* Read and parse the makefile.
802 * Return TRUE if reading the makefile succeeded. */
804 ReadMakefileSucceeded(void *fname, void *unused)
806 return ReadMakefile(fname) == 0;
810 str2Lst_Append(StringList *lp, char *str, const char *sep)
818 for (n = 0, cp = strtok(str, sep); cp; cp = strtok(NULL, sep)) {
828 siginfo(int signo MAKE_ATTR_UNUSED)
830 char dir[MAXPATHLEN];
831 char str[2 * MAXPATHLEN];
833 if (getcwd(dir, sizeof(dir)) == NULL)
835 len = snprintf(str, sizeof(str), "%s: Working in: %s\n", progname, dir);
837 (void)write(STDERR_FILENO, str, (size_t)len);
842 * Allow makefiles some control over the mode we run in.
845 MakeMode(const char *mode)
847 char *mode_freeIt = NULL;
850 (void)Var_Subst("${" MAKE_MODE ":tl}",
851 VAR_GLOBAL, VARE_WANTRES, &mode_freeIt);
852 /* TODO: handle errors */
856 if (mode[0] != '\0') {
857 if (strstr(mode, "compat")) {
858 opts.compatMake = TRUE;
862 if (strstr(mode, "meta"))
863 meta_mode_init(mode);
871 PrintVar(const char *varname, Boolean expandVars)
873 if (strchr(varname, '$')) {
875 (void)Var_Subst(varname, VAR_GLOBAL, VARE_WANTRES, &evalue);
876 /* TODO: handle errors */
877 printf("%s\n", evalue);
880 } else if (expandVars) {
881 char *expr = str_concat3("${", varname, "}");
883 (void)Var_Subst(expr, VAR_GLOBAL, VARE_WANTRES, &evalue);
884 /* TODO: handle errors */
886 printf("%s\n", evalue);
891 const char *value = Var_Value(varname, VAR_GLOBAL, &freeIt);
892 printf("%s\n", value ? value : "");
903 if (opts.printVars == EXPAND_VARS)
905 else if (opts.debugVflag)
908 expandVars = getBoolean(".MAKE.EXPAND_VARIABLES", FALSE);
910 for (ln = opts.variables->first; ln != NULL; ln = ln->next) {
911 const char *varname = ln->datum;
912 PrintVar(varname, expandVars);
919 GNodeList *targs; /* target nodes to create -- passed to Make_Init */
920 Boolean outOfDate; /* FALSE if all targets up to date */
923 * Have now read the entire graph and need to make a list of
924 * targets to create. If none was given on the command line,
925 * we consult the parsing module to find the main target(s)
928 if (Lst_IsEmpty(opts.create))
929 targs = Parse_MainName();
931 targs = Targ_FindList(opts.create);
933 if (!opts.compatMake) {
935 * Initialize job module before traversing the graph
936 * now that any .BEGIN and .END targets have been read.
937 * This is done only if the -q flag wasn't given
938 * (to prevent the .BEGIN from being executed should
941 if (!opts.queryFlag) {
946 /* Traverse the graph, checking on all the targets */
947 outOfDate = Make_Run(targs);
950 * Compat_Init will take care of creating all the
951 * targets as well as initializing the module.
961 * Set up the .TARGETS variable to contain the list of targets to be
962 * created. If none specified, make the variable empty -- the parser
963 * will fill the thing in with the default or .MAIN target.
970 if (Lst_IsEmpty(opts.create)) {
971 Var_Set(".TARGETS", "", VAR_GLOBAL);
975 for (ln = opts.create->first; ln != NULL; ln = ln->next) {
976 char *name = ln->datum;
977 Var_Append(".TARGETS", name, VAR_GLOBAL);
986 gettimeofday(&tv, NULL);
987 srandom((unsigned int)(tv.tv_sec + tv.tv_usec));
991 init_machine(const struct utsname *utsname)
994 const char *machine = FORCE_MACHINE;
996 const char *machine = getenv("MACHINE");
1002 return utsname->machine;
1005 return MAKE_MACHINE;
1013 init_machine_arch(void)
1015 const char *env = getenv("MACHINE_ARCH");
1019 #if defined(MAKE_NATIVE) && defined(CTL_HW)
1021 struct utsname utsname;
1022 static char machine_arch_buf[sizeof(utsname.machine)];
1023 const int mib[2] = { CTL_HW, HW_MACHINE_ARCH };
1024 size_t len = sizeof(machine_arch_buf);
1026 if (sysctl(mib, __arraycount(mib), machine_arch_buf,
1027 &len, NULL, 0) < 0) {
1028 (void)fprintf(stderr, "%s: sysctl failed (%s).\n", progname,
1033 return machine_arch_buf;
1036 #ifndef MACHINE_ARCH
1037 #ifdef MAKE_MACHINE_ARCH
1038 return MAKE_MACHINE_ARCH;
1043 return MACHINE_ARCH;
1048 #ifndef NO_PWD_OVERRIDE
1050 * All this code is so that we know where we are when we start up
1051 * on a different machine with pmake.
1053 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
1054 * since the value of curdir can vary depending on how we got
1055 * here. Ie sitting at a shell prompt (shell that provides $PWD)
1056 * or via subdir.mk in which case its likely a shell which does
1059 * So, to stop it breaking this case only, we ignore PWD if
1060 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a variable expression.
1063 HandlePWD(const struct stat *curdir_st)
1066 void *prefix_freeIt, *makeobjdir_freeIt;
1067 const char *makeobjdir;
1070 if (ignorePWD || (pwd = getenv("PWD")) == NULL)
1073 if (Var_Value("MAKEOBJDIRPREFIX", VAR_CMDLINE, &prefix_freeIt) != NULL) {
1074 bmake_free(prefix_freeIt);
1078 makeobjdir = Var_Value("MAKEOBJDIR", VAR_CMDLINE, &makeobjdir_freeIt);
1079 if (makeobjdir != NULL && strchr(makeobjdir, '$') != NULL)
1082 if (stat(pwd, &pwd_st) == 0 &&
1083 curdir_st->st_ino == pwd_st.st_ino &&
1084 curdir_st->st_dev == pwd_st.st_dev)
1085 (void)strncpy(curdir, pwd, MAXPATHLEN);
1088 bmake_free(makeobjdir_freeIt);
1093 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
1094 * MAKEOBJDIR is set in the environment, try only that value
1095 * and fall back to .CURDIR if it does not exist.
1097 * Otherwise, try _PATH_OBJDIR.MACHINE-MACHINE_ARCH, _PATH_OBJDIR.MACHINE,
1098 * and * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
1099 * of these paths exist, just use .CURDIR.
1102 InitObjdir(const char *machine, const char *machine_arch)
1104 Dir_InitDir(curdir);
1105 (void)Main_SetObjdir("%s", curdir);
1107 if (!Main_SetVarObjdir("MAKEOBJDIRPREFIX", curdir) &&
1108 !Main_SetVarObjdir("MAKEOBJDIR", "") &&
1109 !Main_SetObjdir("%s.%s-%s", _PATH_OBJDIR, machine, machine_arch) &&
1110 !Main_SetObjdir("%s.%s", _PATH_OBJDIR, machine) &&
1111 !Main_SetObjdir("%s", _PATH_OBJDIR))
1112 (void)Main_SetObjdir("%s%s", _PATH_OBJDIRPREFIX, curdir);
1115 /* get rid of resource limit on file descriptors */
1119 #if defined(MAKE_NATIVE) || (defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE))
1121 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
1122 rl.rlim_cur != rl.rlim_max) {
1123 rl.rlim_cur = rl.rlim_max;
1124 (void)setrlimit(RLIMIT_NOFILE, &rl);
1132 opts.compatMake = FALSE; /* No compat mode */
1133 opts.debug = 0; /* No debug verbosity, please. */
1134 /* opts.debug_file has been initialized earlier */
1135 opts.debugVflag = FALSE;
1136 opts.checkEnvFirst = FALSE;
1137 opts.makefiles = Lst_New();
1138 opts.ignoreErrors = FALSE; /* Pay attention to non-zero returns */
1139 opts.maxJobs = DEFMAXLOCAL; /* Set default local max concurrency */
1140 opts.keepgoing = FALSE; /* Stop on error */
1141 opts.noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
1142 opts.noExecute = FALSE; /* Execute all commands */
1143 opts.queryFlag = FALSE; /* This is not just a check-run */
1144 opts.noBuiltins = FALSE; /* Read the built-in rules */
1145 opts.beSilent = FALSE; /* Print commands as executed */
1146 opts.touchFlag = FALSE; /* Actually update targets */
1148 opts.variables = Lst_New();
1149 opts.parseWarnFatal = FALSE;
1150 opts.enterFlag = FALSE;
1151 opts.varNoExportEnv = FALSE;
1152 opts.create = Lst_New();
1155 /* Initialize MAKE and .MAKE to the path of the executable, so that it can be
1156 * found by execvp(3) and the shells, even after a chdir.
1158 * If it's a relative path and contains a '/', resolve it to an absolute path.
1159 * Otherwise keep it as is, assuming it will be found in the PATH. */
1161 InitVarMake(const char *argv0)
1163 const char *make = argv0;
1165 if (argv0[0] != '/' && strchr(argv0, '/') != NULL) {
1166 char pathbuf[MAXPATHLEN];
1167 const char *abs = cached_realpath(argv0, pathbuf);
1169 if (abs != NULL && abs[0] == '/' && stat(make, &st) == 0)
1173 Var_Set("MAKE", make, VAR_GLOBAL);
1174 Var_Set(".MAKE", make, VAR_GLOBAL);
1178 InitDefSysIncPath(char *syspath)
1180 static char defsyspath[] = _PATH_DEFSYSPATH;
1184 * If no user-supplied system path was given (through the -m option)
1185 * add the directories from the DEFSYSPATH (more than one may be given
1186 * as dir1:...:dirn) to the system include path.
1188 /* XXX: mismatch: the -m option sets sysIncPath, not syspath */
1189 if (syspath == NULL || syspath[0] == '\0')
1190 syspath = defsyspath;
1192 syspath = bmake_strdup(syspath);
1194 for (start = syspath; *start != '\0'; start = cp) {
1195 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1200 /* look for magic parent directory search string */
1201 if (strncmp(".../", start, 4) != 0) {
1202 (void)Dir_AddDir(defSysIncPath, start);
1204 char *dir = Dir_FindHereOrAbove(curdir, start + 4);
1206 (void)Dir_AddDir(defSysIncPath, dir);
1212 if (syspath != defsyspath)
1217 ReadBuiltinRules(void)
1219 StringList *sysMkPath = Lst_New();
1220 Dir_Expand(_PATH_DEFSYSMK,
1221 Lst_IsEmpty(sysIncPath) ? defSysIncPath : sysIncPath,
1223 if (Lst_IsEmpty(sysMkPath))
1224 Fatal("%s: no system rules (%s).", progname, _PATH_DEFSYSMK);
1225 if (!Lst_ForEachUntil(sysMkPath, ReadMakefileSucceeded, NULL))
1226 Fatal("%s: cannot open %s.", progname,
1227 (char *)sysMkPath->first->datum);
1228 /* XXX: sysMkPath is not freed */
1237 if (forceJobs || opts.compatMake ||
1238 !Var_Exists(".MAKE.JOBS", VAR_GLOBAL))
1241 (void)Var_Subst("${.MAKE.JOBS}", VAR_GLOBAL, VARE_WANTRES, &value);
1242 /* TODO: handle errors */
1243 n = (int)strtol(value, NULL, 0);
1245 (void)fprintf(stderr,
1246 "%s: illegal value for .MAKE.JOBS "
1247 "-- must be positive integer!\n",
1252 if (n != opts.maxJobs) {
1253 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
1254 Var_Append(MAKEFLAGS, value, VAR_GLOBAL);
1258 maxJobTokens = opts.maxJobs;
1264 * For compatibility, look at the directories in the VPATH variable
1265 * and add them to the search path, if the variable is defined. The
1266 * variable's value is in the same format as the PATH environment
1267 * variable, i.e. <directory>:<directory>:<directory>...
1272 char *vpath, savec, *path;
1273 if (!Var_Exists("VPATH", VAR_CMDLINE))
1276 (void)Var_Subst("${VPATH}", VAR_CMDLINE, VARE_WANTRES, &vpath);
1277 /* TODO: handle errors */
1281 /* skip to end of directory */
1282 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1284 /* Save terminator character so know when to stop */
1287 /* Add directory to search path */
1288 (void)Dir_AddDir(dirSearchPath, path);
1291 } while (savec == ':');
1298 if (opts.makefiles->first != NULL) {
1301 for (ln = opts.makefiles->first; ln != NULL; ln = ln->next) {
1302 if (ReadMakefile(ln->datum) != 0)
1303 Fatal("%s: cannot open %s.",
1304 progname, (char *)ln->datum);
1308 (void)Var_Subst("${" MAKEFILE_PREFERENCE "}",
1309 VAR_CMDLINE, VARE_WANTRES, &p1);
1310 /* TODO: handle errors */
1311 (void)str2Lst_Append(opts.makefiles, p1, NULL);
1312 (void)Lst_ForEachUntil(opts.makefiles,
1313 ReadMakefileSucceeded, NULL);
1322 Lst_Destroy(opts.variables, free);
1323 Lst_Free(opts.makefiles); /* don't free, may be used in GNodes */
1324 Lst_Destroy(opts.create, free);
1327 /* print the graph now it's been processed if the user requested it */
1331 Trace_Log(MAKEEND, 0);
1334 printf("%s: Leaving directory `%s'\n", progname, objdir);
1336 printf("%s: Leaving directory `%s'\n", progname, curdir);
1353 * The main function, for obvious reasons. Initializes variables
1354 * and a few modules, then parses the arguments give it in the
1355 * environment and on the command line. Reads the system makefile
1356 * followed by either Makefile, makefile or the file given by the
1357 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
1358 * flags it has received by then uses either the Make or the Compat
1359 * module to create the initial list of targets.
1362 * If -q was given, exits -1 if anything was out-of-date. Else it exits
1366 * The program exits when done. Targets are created. etc. etc. etc.
1369 main(int argc, char **argv)
1371 Boolean outOfDate; /* FALSE if all targets up to date */
1373 const char *machine;
1374 const char *machine_arch;
1375 char *syspath = getenv("MAKESYSPATH");
1376 struct utsname utsname;
1378 /* default to writing debug to stderr */
1379 opts.debug_file = stderr;
1382 (void)bmake_signal(SIGINFO, siginfo);
1387 if ((progname = strrchr(argv[0], '/')) != NULL)
1394 if (uname(&utsname) == -1) {
1395 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
1401 * Get the name of this type of MACHINE from utsname
1402 * so we can share an executable for similar machines.
1403 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
1405 * Note that both MACHINE and MACHINE_ARCH are decided at
1408 machine = init_machine(&utsname);
1409 machine_arch = init_machine_arch();
1411 myPid = getpid(); /* remember this for vFork() */
1414 * Just in case MAKEOBJDIR wants us to do something tricky.
1416 Var_Init(); /* Initialize the lists of variables for
1417 * parsing arguments */
1418 Var_Set(".MAKE.OS", utsname.sysname, VAR_GLOBAL);
1419 Var_Set("MACHINE", machine, VAR_GLOBAL);
1420 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL);
1422 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL);
1424 Var_Set(".newline", "\n", VAR_GLOBAL); /* handy for :@ loops */
1426 * This is the traditional preference for makefiles.
1428 #ifndef MAKEFILE_PREFERENCE_LIST
1429 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
1431 Var_Set(MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST,
1433 Var_Set(MAKE_DEPENDFILE, ".depend", VAR_GLOBAL);
1436 allPrecious = FALSE; /* Remove targets when interrupted */
1437 deleteOnError = FALSE; /* Historical default behavior */
1438 jobsRunning = FALSE;
1440 maxJobTokens = opts.maxJobs;
1444 * Initialize the parsing, directory and variable modules to prepare
1445 * for the reading of inclusion paths and variable settings on the
1450 * Initialize various variables.
1451 * MAKE also gets this name, for compatibility
1452 * .MAKEFLAGS gets set to the empty string just in case.
1453 * MFLAGS also gets initialized empty, for compatibility.
1456 InitVarMake(argv[0]);
1457 Var_Set(MAKEFLAGS, "", VAR_GLOBAL);
1458 Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL);
1459 Var_Set("MFLAGS", "", VAR_GLOBAL);
1460 Var_Set(".ALLTARGETS", "", VAR_GLOBAL);
1461 /* some makefiles need to know this */
1462 Var_Set(MAKE_LEVEL ".ENV", MAKE_LEVEL_ENV, VAR_CMDLINE);
1465 * Set some other useful macros
1470 makelevel = ((ep = getenv(MAKE_LEVEL_ENV)) && *ep) ? atoi(ep) : 0;
1473 snprintf(tmp, sizeof(tmp), "%d", makelevel);
1474 Var_Set(MAKE_LEVEL, tmp, VAR_GLOBAL);
1475 snprintf(tmp, sizeof(tmp), "%u", myPid);
1476 Var_Set(".MAKE.PID", tmp, VAR_GLOBAL);
1477 snprintf(tmp, sizeof(tmp), "%u", getppid());
1478 Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL);
1480 if (makelevel > 0) {
1482 snprintf(pn, sizeof(pn), "%s[%d]", progname, makelevel);
1483 progname = bmake_strdup(pn);
1492 * First snag any flags out of the MAKE environment variable.
1493 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
1494 * in a different format).
1498 char *p1 = explode(getenv("MAKEFLAGS"));
1499 Main_ParseArgLine(p1);
1503 Main_ParseArgLine(getenv("MAKE"));
1507 * Find where we are (now).
1508 * We take care of PWD for the automounter below...
1510 if (getcwd(curdir, MAXPATHLEN) == NULL) {
1511 (void)fprintf(stderr, "%s: getcwd: %s.\n",
1512 progname, strerror(errno));
1516 MainParseArgs(argc, argv);
1519 printf("%s: Entering directory `%s'\n", progname, curdir);
1522 * Verify that cwd is sane.
1524 if (stat(curdir, &sa) == -1) {
1525 (void)fprintf(stderr, "%s: %s: %s.\n",
1526 progname, curdir, strerror(errno));
1530 #ifndef NO_PWD_OVERRIDE
1533 Var_Set(".CURDIR", curdir, VAR_GLOBAL);
1535 InitObjdir(machine, machine_arch);
1538 * Initialize archive, target and suffix modules in preparation for
1539 * parsing the makefile(s)
1544 Trace_Init(tracefile);
1549 Trace_Log(MAKESTART, NULL);
1553 InitDefSysIncPath(syspath);
1556 * Read in the built-in rules first, followed by the specified
1557 * makefiles, or the default makefile and Makefile, in that order,
1558 * if no makefiles were given on the command line.
1560 if (!opts.noBuiltins)
1564 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1565 if (!opts.noBuiltins || !opts.printVars) {
1566 /* ignore /dev/null and anything starting with "no" */
1567 (void)Var_Subst("${.MAKE.DEPENDFILE:N/dev/null:Nno*:T}",
1568 VAR_CMDLINE, VARE_WANTRES, &makeDependfile);
1569 if (makeDependfile[0] != '\0') {
1570 /* TODO: handle errors */
1571 doing_depend = TRUE;
1572 (void)ReadMakefile(makeDependfile);
1573 doing_depend = FALSE;
1578 printf("%s: Entering directory `%s'\n", progname, objdir);
1584 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &freeIt),
1593 * Be compatible if user did not specify -j and did not explicitly
1594 * turned compatibility on
1596 if (!opts.compatMake && !forceJobs) {
1597 opts.compatMake = TRUE;
1600 if (!opts.compatMake)
1601 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1602 DEBUG5(JOB, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1603 jp_0, jp_1, opts.maxJobs, maxJobTokens, opts.compatMake ? 1 : 0);
1605 if (!opts.printVars)
1606 Main_ExportMAKEFLAGS(TRUE); /* initial export */
1611 * Now that all search paths have been read for suffixes et al, it's
1612 * time to add the default search path to their lists...
1617 * Propagate attributes through :: dependency lists.
1621 /* print the initial graph, if the user requested it */
1625 /* print the values of any variables requested by the user */
1626 if (opts.printVars) {
1630 outOfDate = runTargets();
1635 if (DEBUG(LINT) && (errors > 0 || Parse_GetFatals() > 0))
1636 return 2; /* Not 1 so -q can distinguish error */
1637 return outOfDate ? 1 : 0;
1640 /* Open and parse the given makefile, with all its side effects.
1643 * 0 if ok. -1 if couldn't open file.
1646 ReadMakefile(const char *fname)
1649 char *name, *path = NULL;
1651 if (!strcmp(fname, "-")) {
1652 Parse_File(NULL /*stdin*/, -1);
1653 Var_Set("MAKEFILE", "", VAR_INTERNAL);
1655 /* if we've chdir'd, rebuild the path name */
1656 if (strcmp(curdir, objdir) && *fname != '/') {
1657 path = str_concat3(curdir, "/", fname);
1658 fd = open(path, O_RDONLY);
1665 /* If curdir failed, try objdir (ala .depend) */
1666 path = str_concat3(objdir, "/", fname);
1667 fd = open(path, O_RDONLY);
1673 fd = open(fname, O_RDONLY);
1677 /* look in -I and system include directories. */
1678 name = Dir_FindFile(fname, parseIncPath);
1680 SearchPath *sysInc = Lst_IsEmpty(sysIncPath)
1681 ? defSysIncPath : sysIncPath;
1682 name = Dir_FindFile(fname, sysInc);
1684 if (!name || (fd = open(name, O_RDONLY)) == -1) {
1691 * set the MAKEFILE variable desired by System V fans -- the
1692 * placement of the setting here means it gets set to the last
1693 * makefile specified, as it is set by SysV make.
1697 Var_Set("MAKEFILE", fname, VAR_INTERNAL);
1698 Parse_File(fname, fd);
1708 * Execute the command in cmd, and return the output of that command
1709 * in a string. In the output, newlines are replaced with spaces.
1712 * A string containing the output of the command, or the empty string.
1713 * *errfmt returns a format string describing the command failure,
1714 * if any, using a single %s conversion specification.
1717 * The string must be freed by the caller.
1720 Cmd_Exec(const char *cmd, const char **errfmt)
1722 const char *args[4]; /* Args for invoking the shell */
1723 int fds[2]; /* Pipe streams */
1724 int cpid; /* Child PID */
1725 int pid; /* PID from wait() */
1726 WAIT_T status; /* command exit status */
1727 Buffer buf; /* buffer to store the result */
1729 char *res; /* result */
1732 int savederr; /* saved errno */
1739 * Set up arguments for shell
1741 args[0] = shellName;
1747 * Open a pipe for fetching its output
1749 if (pipe(fds) == -1) {
1750 *errfmt = "Couldn't create pipe for \"%s\"";
1757 switch (cpid = vFork()) {
1760 * Close input side of pipe
1762 (void)close(fds[0]);
1765 * Duplicate the output stream to the shell's output, then
1766 * shut the extra thing down. Note we don't fetch the error
1767 * stream...why not? Why?
1769 (void)dup2(fds[1], 1);
1770 (void)close(fds[1]);
1774 (void)execv(shellPath, UNCONST(args));
1779 *errfmt = "Couldn't exec \"%s\"";
1784 * No need for the writing half
1786 (void)close(fds[1]);
1792 char result[BUFSIZ];
1793 bytes_read = read(fds[0], result, sizeof(result));
1795 Buf_AddBytes(&buf, result, (size_t)bytes_read);
1797 while (bytes_read > 0 || (bytes_read == -1 && errno == EINTR));
1798 if (bytes_read == -1)
1802 * Close the input side of the pipe.
1804 (void)close(fds[0]);
1807 * Wait for the process to exit.
1809 while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) {
1810 JobReapChild(pid, status, FALSE);
1813 res_len = Buf_Len(&buf);
1814 res = Buf_Destroy(&buf, FALSE);
1817 *errfmt = "Couldn't read shell's output for \"%s\"";
1819 if (WIFSIGNALED(status))
1820 *errfmt = "\"%s\" exited on a signal";
1821 else if (WEXITSTATUS(status) != 0)
1822 *errfmt = "\"%s\" returned non-zero status";
1824 /* Convert newlines to spaces. A final newline is just stripped */
1825 if (res_len > 0 && res[res_len - 1] == '\n')
1826 res[res_len - 1] = '\0';
1827 for (cp = res; *cp != '\0'; cp++)
1834 return bmake_strdup("");
1837 /* Print a printf-style error message.
1839 * This error message has no consequences, in particular it does not affect
1840 * the exit status. */
1842 Error(const char *fmt, ...)
1847 err_file = opts.debug_file;
1848 if (err_file == stdout)
1850 (void)fflush(stdout);
1853 fprintf(err_file, "%s: ", progname);
1854 (void)vfprintf(err_file, fmt, ap);
1856 (void)fprintf(err_file, "\n");
1857 (void)fflush(err_file);
1858 if (err_file == stderr)
1865 /* Produce a Fatal error message, then exit immediately.
1867 * If jobs are running, wait for them to finish. */
1869 Fatal(const char *fmt, ...)
1877 (void)fflush(stdout);
1878 (void)vfprintf(stderr, fmt, ap);
1880 (void)fprintf(stderr, "\n");
1881 (void)fflush(stderr);
1883 PrintOnError(NULL, NULL);
1885 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1887 Trace_Log(MAKEERROR, 0);
1888 exit(2); /* Not 1 so -q can distinguish error */
1891 /* Major exception once jobs are being created.
1892 * Kills all jobs, prints a message and exits. */
1894 Punt(const char *fmt, ...)
1899 (void)fflush(stdout);
1900 (void)fprintf(stderr, "%s: ", progname);
1901 (void)vfprintf(stderr, fmt, ap);
1903 (void)fprintf(stderr, "\n");
1904 (void)fflush(stderr);
1906 PrintOnError(NULL, NULL);
1911 /* Exit without giving a message. */
1919 Trace_Log(MAKEERROR, 0);
1920 exit(2); /* Not 1, so -q can distinguish error */
1923 /* Called when aborting due to errors in child shell to signal abnormal exit.
1924 * The program exits.
1925 * Errors is the number of errors encountered in Make_Make. */
1929 if (dieQuietly(NULL, -1))
1931 Fatal("%d error%s", errs, errs == 1 ? "" : "s");
1936 * Remove a file carefully, avoiding directories.
1939 eunlink(const char *file)
1943 if (lstat(file, &st) == -1)
1946 if (S_ISDIR(st.st_mode)) {
1950 return unlink(file);
1954 write_all(int fd, const void *data, size_t n)
1956 const char *mem = data;
1959 ssize_t written = write(fd, mem, n);
1960 if (written == -1 && errno == EAGAIN)
1965 n -= (size_t)written;
1971 * Print why exec failed, avoiding stdio.
1974 execDie(const char *af, const char *av)
1979 Buf_AddStr(&buf, progname);
1980 Buf_AddStr(&buf, ": ");
1981 Buf_AddStr(&buf, af);
1982 Buf_AddStr(&buf, "(");
1983 Buf_AddStr(&buf, av);
1984 Buf_AddStr(&buf, ") failed (");
1985 Buf_AddStr(&buf, strerror(errno));
1986 Buf_AddStr(&buf, ")\n");
1988 write_all(STDERR_FILENO, Buf_GetAll(&buf, NULL), Buf_Len(&buf));
1990 Buf_Destroy(&buf, TRUE);
1996 * exit with usage message
2002 if ((p = strchr(progname, '[')) != NULL)
2005 (void)fprintf(stderr,
2006 "usage: %s [-BeikNnqrstWwX] \n"
2007 " [-C directory] [-D variable] [-d flags] [-f makefile]\n"
2008 " [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n"
2009 " [-V variable] [-v variable] [variable=value] [target ...]\n",
2015 * realpath(3) can get expensive, cache results...
2017 static GNode *cached_realpaths = NULL;
2020 get_cached_realpaths(void)
2023 if (!cached_realpaths) {
2024 cached_realpaths = Targ_NewGN("Realpath");
2025 #ifndef DEBUG_REALPATH_CACHE
2026 cached_realpaths->flags = INTERNAL;
2030 return cached_realpaths;
2033 /* purge any relative paths */
2035 purge_cached_realpaths(void)
2037 GNode *cache = get_cached_realpaths();
2038 HashEntry *he, *nhe;
2041 HashIter_Init(&hi, &cache->context);
2042 he = HashIter_Next(&hi);
2043 while (he != NULL) {
2044 nhe = HashIter_Next(&hi);
2045 if (he->key[0] != '/') {
2047 fprintf(stderr, "cached_realpath: purging %s\n", he->key);
2048 HashTable_DeleteEntry(&cache->context, he);
2055 cached_realpath(const char *pathname, char *resolved)
2061 if (!pathname || !pathname[0])
2064 cache = get_cached_realpaths();
2066 if ((rp = Var_Value(pathname, cache, &freeIt)) != NULL) {
2068 strlcpy(resolved, rp, MAXPATHLEN);
2069 } else if ((rp = realpath(pathname, resolved)) != NULL) {
2070 Var_Set(pathname, rp, cache);
2071 } /* else should we negative-cache? */
2074 return rp ? resolved : NULL;
2078 * Return true if we should die without noise.
2079 * For example our failing child was a sub-make
2080 * or failure happend elsewhere.
2083 dieQuietly(GNode *gn, int bf)
2085 static int quietly = -1;
2088 if (DEBUG(JOB) || !getBoolean(".MAKE.DIE_QUIETLY", TRUE))
2093 quietly = gn != NULL ? ((gn->type & (OP_MAKE)) != 0) : 0;
2099 SetErrorVars(GNode *gn)
2104 * We can print this even if there is no .ERROR target.
2106 Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL);
2107 Var_Delete(".ERROR_CMD", VAR_GLOBAL);
2109 for (ln = gn->commands->first; ln != NULL; ln = ln->next) {
2110 const char *cmd = ln->datum;
2114 Var_Append(".ERROR_CMD", cmd, VAR_GLOBAL);
2119 PrintOnError(GNode *gn, const char *s)
2121 static GNode *en = NULL;
2130 /* we generally want to keep quiet if a sub-make died */
2131 if (dieQuietly(gn, -1))
2137 printf("\n%s: stopped in %s\n", progname, curdir);
2140 return; /* we've been here! */
2143 expr = "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}";
2144 (void)Var_Subst(expr, VAR_GLOBAL, VARE_WANTRES, &cp);
2145 /* TODO: handle errors */
2151 * Finally, see if there is a .ERROR target, and run it if so.
2153 en = Targ_FindNode(".ERROR");
2155 en->type |= OP_SPECIAL;
2156 Compat_Make(en, en);
2161 Main_ExportMAKEFLAGS(Boolean first)
2163 static Boolean once = TRUE;
2171 expr = "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}";
2172 (void)Var_Subst(expr, VAR_CMDLINE, VARE_WANTRES, &s);
2173 /* TODO: handle errors */
2176 setenv("MAKEFLAGS", s, 1);
2178 setenv("MAKE", s, 1);
2186 static char *tmpdir = NULL;
2192 * Honor $TMPDIR but only if it is valid.
2193 * Ensure it ends with /.
2195 (void)Var_Subst("${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL,
2196 VARE_WANTRES, &tmpdir);
2197 /* TODO: handle errors */
2198 if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
2200 tmpdir = bmake_strdup(_PATH_TMP);
2207 * Create and open a temp file using "pattern".
2208 * If out_fname is provided, set it to a copy of the filename created.
2209 * Otherwise unlink the file once open.
2212 mkTempFile(const char *pattern, char **out_fname)
2214 static char *tmpdir = NULL;
2215 char tfile[MAXPATHLEN];
2218 if (pattern != NULL)
2221 tmpdir = getTmpdir();
2222 if (pattern[0] == '/') {
2223 snprintf(tfile, sizeof(tfile), "%s", pattern);
2225 snprintf(tfile, sizeof(tfile), "%s%s", tmpdir, pattern);
2227 if ((fd = mkstemp(tfile)) < 0)
2228 Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
2230 *out_fname = bmake_strdup(tfile);
2232 unlink(tfile); /* we just want the descriptor */
2238 * Convert a string representation of a boolean.
2239 * Anything that looks like "No", "False", "Off", "0" etc,
2240 * is FALSE, otherwise TRUE.
2243 s2Boolean(const char *s, Boolean bf)
2246 case '\0': /* not set - the default wins */
2256 return s[1] != 'F' && s[1] != 'f';
2264 * Return a Boolean based on a variable.
2266 * If the knob is not set, return the fallback.
2267 * If set, anything that looks or smells like "No", "False", "Off", "0", etc.
2268 * is FALSE, otherwise TRUE.
2271 getBoolean(const char *varname, Boolean fallback)
2273 char *expr = str_concat3("${", varname, ":U}");
2277 (void)Var_Subst(expr, VAR_GLOBAL, VARE_WANTRES, &value);
2278 /* TODO: handle errors */
2279 res = s2Boolean(value, fallback);