1 /* $NetBSD: main.c,v 1.210 2013/03/23 05:31:29 sjg 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.210 2013/03/23 05:31:29 sjg 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.210 2013/03/23 05:31:29 sjg 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 two optional
105 * Fatal Print an error message and exit. Also takes
106 * a format string and two arguments.
108 * Punt Aborts all jobs and exits with a message. Also
109 * takes a format string and two arguments.
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>
121 #include <sys/stat.h>
122 #include <sys/utsname.h>
136 #include "pathnames.h"
144 #define DEFMAXLOCAL DEFMAXJOBS
145 #endif /* DEFMAXLOCAL */
147 Lst create; /* Targets to be made */
148 time_t now; /* Time at start of make */
149 GNode *DEFAULT; /* .DEFAULT node */
150 Boolean allPrecious; /* .PRECIOUS given on line by itself */
152 static Boolean noBuiltins; /* -r flag */
153 static Lst makefiles; /* ordered list of makefiles to read */
154 static Boolean printVars; /* print value of one or more vars */
155 static Lst variables; /* list of variables to print */
156 int maxJobs; /* -j argument */
157 static int maxJobTokens; /* -j argument */
158 Boolean compatMake; /* -B argument */
159 int debug; /* -d argument */
160 Boolean debugVflag; /* -dV */
161 Boolean noExecute; /* -n flag */
162 Boolean noRecursiveExecute; /* -N flag */
163 Boolean keepgoing; /* -k flag */
164 Boolean queryFlag; /* -q flag */
165 Boolean touchFlag; /* -t flag */
166 Boolean ignoreErrors; /* -i flag */
167 Boolean beSilent; /* -s flag */
168 Boolean oldVars; /* variable substitution style */
169 Boolean checkEnvFirst; /* -e flag */
170 Boolean parseWarnFatal; /* -W flag */
171 Boolean jobServer; /* -J flag */
172 static int jp_0 = -1, jp_1 = -1; /* ends of parent job pipe */
173 Boolean varNoExportEnv; /* -X flag */
174 Boolean doing_depend; /* Set while reading .depend */
175 static Boolean jobsRunning; /* TRUE if the jobs might be running */
176 static const char * tracefile;
177 static void MainParseArgs(int, char **);
178 static int ReadMakefile(const void *, const void *);
179 static void usage(void) MAKE_ATTR_DEAD;
181 static Boolean ignorePWD; /* if we use -C, PWD is meaningless */
182 static char objdir[MAXPATHLEN + 1]; /* where we chdir'ed to */
183 char curdir[MAXPATHLEN + 1]; /* Startup directory */
184 char *progname; /* the program name */
185 char *makeDependfile;
188 Boolean forceJobs = FALSE;
191 * On some systems MACHINE is defined as something other than
196 # define MACHINE FORCE_MACHINE
199 extern Lst parseIncPath;
202 parse_debug_options(const char *argvalue)
209 for (modules = argvalue; *modules; ++modules) {
227 debug |= DEBUG_ERROR;
233 if (modules[1] == '1') {
234 debug |= DEBUG_GRAPH1;
237 else if (modules[1] == '2') {
238 debug |= DEBUG_GRAPH2;
241 else if (modules[1] == '3') {
242 debug |= DEBUG_GRAPH3;
259 debug |= DEBUG_SCRIPT;
262 debug |= DEBUG_PARSE;
277 debug |= DEBUG_SHELL;
280 if (debug_file != stdout && debug_file != stderr)
282 if (*++modules == '+') {
287 if (strcmp(modules, "stdout") == 0) {
291 if (strcmp(modules, "stderr") == 0) {
295 len = strlen(modules);
296 fname = malloc(len + 20);
297 memcpy(fname, modules, len + 1);
298 /* Let the filename be modified by the pid */
299 if (strcmp(fname + len - 3, ".%d") == 0)
300 snprintf(fname + len - 2, 20, "%d", getpid());
301 debug_file = fopen(fname, mode);
303 fprintf(stderr, "Cannot open debug file %s\n",
310 (void)fprintf(stderr,
311 "%s: illegal argument to d option -- %c\n",
318 * Make the debug_file unbuffered, and make
319 * stdout line buffered (unless debugfile == stdout).
321 setvbuf(debug_file, NULL, _IONBF, 0);
322 if (debug_file != stdout) {
323 setvbuf(stdout, NULL, _IOLBF, 0);
329 * Parse a given argument vector. Called from main() and from
330 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
332 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
338 * Various global and local flags will be set depending on the flags
342 MainParseArgs(int argc, char **argv)
348 const char *getopt_def;
350 Boolean inOption, dashDash = FALSE;
351 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
353 #define OPTFLAGS "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrst"
354 /* Can't actually use getopt(3) because rescanning is not portable */
356 getopt_def = OPTFLAGS;
374 if (c != '-' || dashDash)
379 /* '-' found at some earlier point */
380 getopt_spec = strchr(getopt_def, c);
381 if(c != '\0' && getopt_spec != NULL && getopt_spec[1] == ':') {
382 /* -<something> found, and <something> should have an arg */
386 if(*argvalue == '\0') {
402 Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
403 Var_Set(MAKE_MODE, "compat", VAR_GLOBAL, 0);
406 if (chdir(argvalue) == -1) {
407 (void)fprintf(stderr,
408 "%s: chdir %s: %s\n",
413 if (getcwd(curdir, MAXPATHLEN) == NULL) {
414 (void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
420 if (argvalue == NULL || argvalue[0] == 0) goto noarg;
421 Var_Set(argvalue, "1", VAR_GLOBAL, 0);
422 Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
423 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
426 if (argvalue == NULL) goto noarg;
427 Parse_AddIncludeDir(argvalue);
428 Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
429 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
432 if (argvalue == NULL) goto noarg;
433 if (sscanf(argvalue, "%d,%d", &jp_0, &jp_1) != 2) {
434 (void)fprintf(stderr,
435 "%s: internal error -- J option malformed (%s)\n",
439 if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
440 (fcntl(jp_1, F_GETFD, 0) < 0)) {
442 (void)fprintf(stderr,
443 "%s: ###### warning -- J descriptors were closed!\n",
451 Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
452 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
458 noRecursiveExecute = TRUE;
459 Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
463 Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
466 if (argvalue == NULL) goto noarg;
467 tracefile = bmake_strdup(argvalue);
468 Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
469 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
472 if (argvalue == NULL) goto noarg;
474 (void)Lst_AtEnd(variables, argvalue);
475 Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
476 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
479 parseWarnFatal = TRUE;
482 varNoExportEnv = TRUE;
483 Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
486 if (argvalue == NULL) goto noarg;
487 /* If '-d-opts' don't pass to children */
488 if (argvalue[0] == '-')
491 Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
492 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
494 parse_debug_options(argvalue);
497 checkEnvFirst = TRUE;
498 Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
501 if (argvalue == NULL) goto noarg;
502 (void)Lst_AtEnd(makefiles, argvalue);
506 Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
509 if (argvalue == NULL) goto noarg;
511 maxJobs = strtol(argvalue, &p, 0);
512 if (*p != '\0' || maxJobs < 1) {
513 (void)fprintf(stderr, "%s: illegal argument to -j -- must be positive integer!\n",
517 Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
518 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
519 Var_Set(".MAKE.JOBS", argvalue, VAR_GLOBAL, 0);
520 maxJobTokens = maxJobs;
524 Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
527 if (argvalue == NULL) goto noarg;
528 /* look for magic parent directory search string */
529 if (strncmp(".../", argvalue, 4) == 0) {
530 if (!Dir_FindHereOrAbove(curdir, argvalue+4,
531 found_path, sizeof(found_path)))
532 break; /* nothing doing */
533 (void)Dir_AddDir(sysIncPath, found_path);
535 (void)Dir_AddDir(sysIncPath, argvalue);
537 Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
538 Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
542 Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
546 /* Kind of nonsensical, wot? */
547 Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
551 Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
555 Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
559 Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
567 fprintf(stderr, "getopt(%s) -> %d (%c)\n",
579 * See if the rest of the arguments are variable assignments and
580 * perform them if so. Else take them to be targets and stuff them
581 * on the end of the "create" list.
583 for (; argc > 1; ++argv, --argc)
584 if (Parse_IsVar(argv[1])) {
585 Parse_DoVar(argv[1], VAR_CMD);
588 Punt("illegal (null) argument.");
589 if (*argv[1] == '-' && !dashDash)
591 (void)Lst_AtEnd(create, bmake_strdup(argv[1]));
596 (void)fprintf(stderr, "%s: option requires an argument -- %c\n",
602 * Main_ParseArgLine --
603 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
604 * is encountered and by main() when reading the .MAKEFLAGS envariable.
605 * Takes a line of arguments and breaks it into its
606 * component words and passes those words and the number of them to the
607 * MainParseArgs function.
608 * The line should have all its leading whitespace removed.
611 * line Line to fracture
617 * Only those that come from the various arguments.
620 Main_ParseArgLine(const char *line)
622 char **argv; /* Manufactured argument vector */
623 int argc; /* Number of arguments in argv */
624 char *args; /* Space used by the args */
626 char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
631 for (; *line == ' '; ++line)
639 * $MAKE may simply be naming the make(1) binary
643 if (!(cp = strrchr(line, '/')))
645 if ((cp = strstr(cp, "make")) &&
646 strcmp(cp, "make") == 0)
650 buf = bmake_malloc(len = strlen(line) + strlen(argv0) + 2);
651 (void)snprintf(buf, len, "%s %s", argv0, line);
655 argv = brk_string(buf, &argc, TRUE, &args);
657 Error("Unterminated quoted string [%s]", buf);
662 MainParseArgs(argc, argv);
669 Main_SetObjdir(const char *path)
673 char buf[MAXPATHLEN + 1];
676 /* expand variable substitutions */
677 if (strchr(path, '$') != 0) {
678 snprintf(buf, MAXPATHLEN, "%s", path);
679 path = p = Var_Subst(NULL, buf, VAR_GLOBAL, 0);
682 if (path[0] != '/') {
683 snprintf(buf, MAXPATHLEN, "%s/%s", curdir, path);
687 /* look for the directory and try to chdir there */
688 if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
690 (void)fprintf(stderr, "make warning: %s: %s.\n",
691 path, strerror(errno));
693 strncpy(objdir, path, MAXPATHLEN);
694 Var_Set(".OBJDIR", objdir, VAR_GLOBAL, 0);
695 setenv("PWD", objdir, 1);
707 * ReadAllMakefiles --
708 * wrapper around ReadMakefile() to read all.
711 * TRUE if ok, FALSE on error
714 ReadAllMakefiles(const void *p, const void *q)
716 return (ReadMakefile(p, q) == 0);
720 str2Lst_Append(Lst lp, char *str, const char *sep)
728 for (n = 0, cp = strtok(str, sep); cp; cp = strtok(NULL, sep)) {
729 (void)Lst_AtEnd(lp, cp);
738 siginfo(int signo MAKE_ATTR_UNUSED)
740 char dir[MAXPATHLEN];
741 char str[2 * MAXPATHLEN];
743 if (getcwd(dir, sizeof(dir)) == NULL)
745 len = snprintf(str, sizeof(str), "%s: Working in: %s\n", progname, dir);
747 (void)write(STDERR_FILENO, str, (size_t)len);
752 * Allow makefiles some control over the mode we run in.
755 MakeMode(const char *mode)
760 mode = mp = Var_Subst(NULL, "${" MAKE_MODE ":tl}", VAR_GLOBAL, 0);
763 if (strstr(mode, "compat")) {
768 if (strstr(mode, "meta"))
769 meta_mode_init(mode);
778 * The main function, for obvious reasons. Initializes variables
779 * and a few modules, then parses the arguments give it in the
780 * environment and on the command line. Reads the system makefile
781 * followed by either Makefile, makefile or the file given by the
782 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
783 * flags it has received by then uses either the Make or the Compat
784 * module to create the initial list of targets.
787 * If -q was given, exits -1 if anything was out-of-date. Else it exits
791 * The program exits when done. Targets are created. etc. etc. etc.
794 main(int argc, char **argv)
796 Lst targs; /* target nodes to create -- passed to Make_Init */
797 Boolean outOfDate = FALSE; /* FALSE if all targets up to date */
799 char *p1, *path, *pwd;
800 char mdpath[MAXPATHLEN];
802 const char *machine = FORCE_MACHINE;
804 const char *machine = getenv("MACHINE");
806 const char *machine_arch = getenv("MACHINE_ARCH");
807 char *syspath = getenv("MAKESYSPATH");
808 Lst sysMkPath; /* Path of sys.mk */
809 char *cp = NULL, *start;
810 /* avoid faults on read-only strings */
811 static char defsyspath[] = _PATH_DEFSYSPATH;
812 char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
813 struct timeval rightnow; /* to initialize random seed */
814 struct utsname utsname;
816 /* default to writing debug to stderr */
820 (void)bmake_signal(SIGINFO, siginfo);
823 * Set the seed to produce a different random sequence
824 * on each program execution.
826 gettimeofday(&rightnow, NULL);
827 srandom(rightnow.tv_sec + rightnow.tv_usec);
829 if ((progname = strrchr(argv[0], '/')) != NULL)
833 #if defined(MAKE_NATIVE) || (defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE))
835 * get rid of resource limit on file descriptors
839 if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
840 rl.rlim_cur != rl.rlim_max) {
841 rl.rlim_cur = rl.rlim_max;
842 (void)setrlimit(RLIMIT_NOFILE, &rl);
847 if (uname(&utsname) == -1) {
848 (void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
854 * Get the name of this type of MACHINE from utsname
855 * so we can share an executable for similar machines.
856 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
858 * Note that both MACHINE and MACHINE_ARCH are decided at
863 machine = utsname.machine;
866 machine = MAKE_MACHINE;
875 #ifdef MAKE_MACHINE_ARCH
876 machine_arch = MAKE_MACHINE_ARCH;
878 machine_arch = "unknown";
881 machine_arch = MACHINE_ARCH;
885 myPid = getpid(); /* remember this for vFork() */
888 * Just in case MAKEOBJDIR wants us to do something tricky.
890 Var_Init(); /* Initialize the lists of variables for
891 * parsing arguments */
892 Var_Set(".MAKE.OS", utsname.sysname, VAR_GLOBAL, 0);
893 Var_Set("MACHINE", machine, VAR_GLOBAL, 0);
894 Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL, 0);
896 Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL, 0);
898 Var_Set(".newline", "\n", VAR_GLOBAL, 0); /* handy for :@ loops */
900 * This is the traditional preference for makefiles.
902 #ifndef MAKEFILE_PREFERENCE_LIST
903 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
905 Var_Set(MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST,
907 Var_Set(MAKE_DEPENDFILE, ".depend", VAR_GLOBAL, 0);
909 create = Lst_Init(FALSE);
910 makefiles = Lst_Init(FALSE);
913 variables = Lst_Init(FALSE);
914 beSilent = FALSE; /* Print commands as executed */
915 ignoreErrors = FALSE; /* Pay attention to non-zero returns */
916 noExecute = FALSE; /* Execute all commands */
917 noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
918 keepgoing = FALSE; /* Stop on error */
919 allPrecious = FALSE; /* Remove targets when interrupted */
920 queryFlag = FALSE; /* This is not just a check-run */
921 noBuiltins = FALSE; /* Read the built-in rules */
922 touchFlag = FALSE; /* Actually update targets */
923 debug = 0; /* No debug verbosity, please. */
926 maxJobs = DEFMAXLOCAL; /* Set default local max concurrency */
927 maxJobTokens = maxJobs;
928 compatMake = FALSE; /* No compat mode */
932 * Initialize the parsing, directory and variable modules to prepare
933 * for the reading of inclusion paths and variable settings on the
938 * Initialize various variables.
939 * MAKE also gets this name, for compatibility
940 * .MAKEFLAGS gets set to the empty string just in case.
941 * MFLAGS also gets initialized empty, for compatibility.
944 if (argv[0][0] == '/' || strchr(argv[0], '/') == NULL) {
946 * Leave alone if it is an absolute path, or if it does
947 * not contain a '/' in which case we need to find it in
948 * the path, like execvp(3) and the shells do.
953 * A relative path, canonicalize it.
955 p1 = realpath(argv[0], mdpath);
956 if (!p1 || *p1 != '/' || stat(p1, &sb) < 0) {
957 p1 = argv[0]; /* realpath failed */
960 Var_Set("MAKE", p1, VAR_GLOBAL, 0);
961 Var_Set(".MAKE", p1, VAR_GLOBAL, 0);
962 Var_Set(MAKEFLAGS, "", VAR_GLOBAL, 0);
963 Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL, 0);
964 Var_Set("MFLAGS", "", VAR_GLOBAL, 0);
965 Var_Set(".ALLTARGETS", "", VAR_GLOBAL, 0);
968 * Set some other useful macros
974 if (!(ep = getenv(MAKE_LEVEL))) {
975 #ifdef MAKE_LEVEL_SAFE
976 if (!(ep = getenv(MAKE_LEVEL_SAFE)))
980 Var_Set(MAKE_LEVEL, ep, VAR_GLOBAL, 0);
981 snprintf(tmp, sizeof(tmp), "%u", myPid);
982 Var_Set(".MAKE.PID", tmp, VAR_GLOBAL, 0);
983 snprintf(tmp, sizeof(tmp), "%u", getppid());
984 Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL, 0);
992 * First snag any flags out of the MAKE environment variable.
993 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
994 * in a different format).
997 Main_ParseArgLine(getenv("MAKEFLAGS"));
999 Main_ParseArgLine(getenv("MAKE"));
1003 * Find where we are (now).
1004 * We take care of PWD for the automounter below...
1006 if (getcwd(curdir, MAXPATHLEN) == NULL) {
1007 (void)fprintf(stderr, "%s: getcwd: %s.\n",
1008 progname, strerror(errno));
1012 MainParseArgs(argc, argv);
1015 * Verify that cwd is sane.
1017 if (stat(curdir, &sa) == -1) {
1018 (void)fprintf(stderr, "%s: %s: %s.\n",
1019 progname, curdir, strerror(errno));
1024 * All this code is so that we know where we are when we start up
1025 * on a different machine with pmake.
1026 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
1027 * since the value of curdir can vary depending on how we got
1028 * here. Ie sitting at a shell prompt (shell that provides $PWD)
1029 * or via subdir.mk in which case its likely a shell which does
1031 * So, to stop it breaking this case only, we ignore PWD if
1032 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
1034 #ifndef NO_PWD_OVERRIDE
1036 (pwd = getenv("PWD")) != NULL &&
1037 getenv("MAKEOBJDIRPREFIX") == NULL) {
1038 const char *makeobjdir = getenv("MAKEOBJDIR");
1040 if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
1041 if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
1042 sa.st_dev == sb.st_dev)
1043 (void)strncpy(curdir, pwd, MAXPATHLEN);
1047 Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0);
1050 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
1051 * MAKEOBJDIR is set in the environment, try only that value
1052 * and fall back to .CURDIR if it does not exist.
1054 * Otherwise, try _PATH_OBJDIR.MACHINE, _PATH_OBJDIR, and
1055 * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
1056 * of these paths exist, just use .CURDIR.
1059 (void)Main_SetObjdir(curdir);
1061 if ((path = getenv("MAKEOBJDIRPREFIX")) != NULL) {
1062 (void)snprintf(mdpath, MAXPATHLEN, "%s%s", path, curdir);
1063 (void)Main_SetObjdir(mdpath);
1064 } else if ((path = getenv("MAKEOBJDIR")) != NULL) {
1065 (void)Main_SetObjdir(path);
1067 (void)snprintf(mdpath, MAXPATHLEN, "%s.%s", _PATH_OBJDIR, machine);
1068 if (!Main_SetObjdir(mdpath) && !Main_SetObjdir(_PATH_OBJDIR)) {
1069 (void)snprintf(mdpath, MAXPATHLEN, "%s%s",
1070 _PATH_OBJDIRPREFIX, curdir);
1071 (void)Main_SetObjdir(mdpath);
1076 * Be compatible if user did not specify -j and did not explicitly
1077 * turned compatibility on
1079 if (!compatMake && !forceJobs) {
1084 * Initialize archive, target and suffix modules in preparation for
1085 * parsing the makefile(s)
1090 Trace_Init(tracefile);
1095 Trace_Log(MAKESTART, NULL);
1098 * Set up the .TARGETS variable to contain the list of targets to be
1099 * created. If none specified, make the variable empty -- the parser
1100 * will fill the thing in with the default or .MAIN target.
1102 if (!Lst_IsEmpty(create)) {
1105 for (ln = Lst_First(create); ln != NULL;
1106 ln = Lst_Succ(ln)) {
1107 char *name = (char *)Lst_Datum(ln);
1109 Var_Append(".TARGETS", name, VAR_GLOBAL);
1112 Var_Set(".TARGETS", "", VAR_GLOBAL, 0);
1116 * If no user-supplied system path was given (through the -m option)
1117 * add the directories from the DEFSYSPATH (more than one may be given
1118 * as dir1:...:dirn) to the system include path.
1120 if (syspath == NULL || *syspath == '\0')
1121 syspath = defsyspath;
1123 syspath = bmake_strdup(syspath);
1125 for (start = syspath; *start != '\0'; start = cp) {
1126 for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1131 /* look for magic parent directory search string */
1132 if (strncmp(".../", start, 4) != 0) {
1133 (void)Dir_AddDir(defIncPath, start);
1135 if (Dir_FindHereOrAbove(curdir, start+4,
1136 found_path, sizeof(found_path))) {
1137 (void)Dir_AddDir(defIncPath, found_path);
1141 if (syspath != defsyspath)
1145 * Read in the built-in rules first, followed by the specified
1146 * makefile, if it was (makefile != NULL), or the default
1147 * makefile and Makefile, in that order, if it wasn't.
1152 sysMkPath = Lst_Init(FALSE);
1153 Dir_Expand(_PATH_DEFSYSMK,
1154 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
1156 if (Lst_IsEmpty(sysMkPath))
1157 Fatal("%s: no system rules (%s).", progname,
1159 ln = Lst_Find(sysMkPath, NULL, ReadMakefile);
1161 Fatal("%s: cannot open %s.", progname,
1162 (char *)Lst_Datum(ln));
1165 if (!Lst_IsEmpty(makefiles)) {
1168 ln = Lst_Find(makefiles, NULL, ReadAllMakefiles);
1170 Fatal("%s: cannot open %s.", progname,
1171 (char *)Lst_Datum(ln));
1173 p1 = Var_Subst(NULL, "${" MAKEFILE_PREFERENCE "}",
1176 (void)str2Lst_Append(makefiles, p1, NULL);
1177 (void)Lst_Find(makefiles, NULL, ReadMakefile);
1182 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1183 if (!noBuiltins || !printVars) {
1184 makeDependfile = Var_Subst(NULL, "${.MAKE.DEPENDFILE:T}",
1186 doing_depend = TRUE;
1187 (void)ReadMakefile(makeDependfile, NULL);
1188 doing_depend = FALSE;
1193 Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
1198 Job_ServerStart(maxJobTokens, jp_0, jp_1);
1200 fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1201 jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
1203 Main_ExportMAKEFLAGS(TRUE); /* initial export */
1206 * For compatibility, look at the directories in the VPATH variable
1207 * and add them to the search path, if the variable is defined. The
1208 * variable's value is in the same format as the PATH envariable, i.e.
1209 * <directory>:<directory>:<directory>...
1211 if (Var_Exists("VPATH", VAR_CMD)) {
1214 * GCC stores string constants in read-only memory, but
1215 * Var_Subst will want to write this thing, so store it
1218 static char VPATH[] = "${VPATH}";
1220 vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
1223 /* skip to end of directory */
1224 for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1226 /* Save terminator character so know when to stop */
1229 /* Add directory to search path */
1230 (void)Dir_AddDir(dirSearchPath, path);
1233 } while (savec == ':');
1238 * Now that all search paths have been read for suffixes et al, it's
1239 * time to add the default search path to their lists...
1244 * Propagate attributes through :: dependency lists.
1248 /* print the initial graph, if the user requested it */
1252 /* print the values of any variables requested by the user */
1260 expandVars = getBoolean(".MAKE.EXPAND_VARIABLES", FALSE);
1261 for (ln = Lst_First(variables); ln != NULL;
1262 ln = Lst_Succ(ln)) {
1263 char *var = (char *)Lst_Datum(ln);
1266 if (strchr(var, '$')) {
1267 value = p1 = Var_Subst(NULL, var, VAR_GLOBAL, 0);
1268 } else if (expandVars) {
1271 if (snprintf(tmp, sizeof(tmp), "${%s}", var) >= (int)(sizeof(tmp)))
1272 Fatal("%s: variable name too big: %s",
1274 value = p1 = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1276 value = Var_Value(var, VAR_GLOBAL, &p1);
1278 printf("%s\n", value ? value : "");
1284 * Have now read the entire graph and need to make a list of
1285 * targets to create. If none was given on the command line,
1286 * we consult the parsing module to find the main target(s)
1289 if (Lst_IsEmpty(create))
1290 targs = Parse_MainName();
1292 targs = Targ_FindList(create, TARG_CREATE);
1296 * Initialize job module before traversing the graph
1297 * now that any .BEGIN and .END targets have been read.
1298 * This is done only if the -q flag wasn't given
1299 * (to prevent the .BEGIN from being executed should
1307 /* Traverse the graph, checking on all the targets */
1308 outOfDate = Make_Run(targs);
1311 * Compat_Init will take care of creating all the
1312 * targets as well as initializing the module.
1319 Lst_Destroy(targs, NULL);
1320 Lst_Destroy(variables, NULL);
1321 Lst_Destroy(makefiles, NULL);
1322 Lst_Destroy(create, (FreeProc *)free);
1325 /* print the graph now it's been processed if the user requested it */
1329 Trace_Log(MAKEEND, 0);
1340 return outOfDate ? 1 : 0;
1345 * Open and parse the given makefile.
1348 * 0 if ok. -1 if couldn't open file.
1354 ReadMakefile(const void *p, const void *q MAKE_ATTR_UNUSED)
1356 const char *fname = p; /* makefile to read */
1358 size_t len = MAXPATHLEN;
1359 char *name, *path = bmake_malloc(len);
1361 if (!strcmp(fname, "-")) {
1362 Parse_File(NULL /*stdin*/, -1);
1363 Var_Set("MAKEFILE", "", VAR_GLOBAL, 0);
1365 /* if we've chdir'd, rebuild the path name */
1366 if (strcmp(curdir, objdir) && *fname != '/') {
1367 size_t plen = strlen(curdir) + strlen(fname) + 2;
1369 path = bmake_realloc(path, len = 2 * plen);
1371 (void)snprintf(path, len, "%s/%s", curdir, fname);
1372 fd = open(path, O_RDONLY);
1378 /* If curdir failed, try objdir (ala .depend) */
1379 plen = strlen(objdir) + strlen(fname) + 2;
1381 path = bmake_realloc(path, len = 2 * plen);
1382 (void)snprintf(path, len, "%s/%s", objdir, fname);
1383 fd = open(path, O_RDONLY);
1389 fd = open(fname, O_RDONLY);
1393 /* look in -I and system include directories. */
1394 name = Dir_FindFile(fname, parseIncPath);
1396 name = Dir_FindFile(fname,
1397 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1398 if (!name || (fd = open(name, O_RDONLY)) == -1) {
1406 * set the MAKEFILE variable desired by System V fans -- the
1407 * placement of the setting here means it gets set to the last
1408 * makefile specified, as it is set by SysV make.
1412 Var_Set("MAKEFILE", fname, VAR_GLOBAL, 0);
1413 Parse_File(fname, fd);
1423 * Execute the command in cmd, and return the output of that command
1427 * A string containing the output of the command, or the empty string
1428 * If errnum is not NULL, it contains the reason for the command failure
1431 * The string must be freed by the caller.
1434 Cmd_Exec(const char *cmd, const char **errnum)
1436 const char *args[4]; /* Args for invoking the shell */
1437 int fds[2]; /* Pipe streams */
1438 int cpid; /* Child PID */
1439 int pid; /* PID from wait() */
1440 char *res; /* result */
1441 WAIT_T status; /* command exit status */
1442 Buffer buf; /* buffer to store the result */
1452 * Set up arguments for shell
1454 args[0] = shellName;
1460 * Open a pipe for fetching its output
1462 if (pipe(fds) == -1) {
1463 *errnum = "Couldn't create pipe for \"%s\"";
1470 switch (cpid = vFork()) {
1473 * Close input side of pipe
1475 (void)close(fds[0]);
1478 * Duplicate the output stream to the shell's output, then
1479 * shut the extra thing down. Note we don't fetch the error
1480 * stream...why not? Why?
1482 (void)dup2(fds[1], 1);
1483 (void)close(fds[1]);
1487 (void)execv(shellPath, UNCONST(args));
1492 *errnum = "Couldn't exec \"%s\"";
1497 * No need for the writing half
1499 (void)close(fds[1]);
1504 char result[BUFSIZ];
1505 cc = read(fds[0], result, sizeof(result));
1507 Buf_AddBytes(&buf, cc, result);
1509 while (cc > 0 || (cc == -1 && errno == EINTR));
1512 * Close the input side of the pipe.
1514 (void)close(fds[0]);
1517 * Wait for the process to exit.
1519 while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) {
1520 JobReapChild(pid, status, FALSE);
1523 cc = Buf_Size(&buf);
1524 res = Buf_Destroy(&buf, FALSE);
1527 *errnum = "Couldn't read shell's output for \"%s\"";
1529 if (WIFSIGNALED(status))
1530 *errnum = "\"%s\" exited on a signal";
1531 else if (WEXITSTATUS(status) != 0)
1532 *errnum = "\"%s\" returned non-zero status";
1535 * Null-terminate the result, convert newlines to spaces and
1536 * install it in the variable.
1541 if (cc > 0 && *--cp == '\n') {
1543 * A final newline is just stripped
1557 res = bmake_malloc(1);
1564 * Print an error message given its format.
1570 * The message is printed.
1574 Error(const char *fmt, ...)
1579 err_file = debug_file;
1580 if (err_file == stdout)
1582 (void)fflush(stdout);
1585 fprintf(err_file, "%s: ", progname);
1586 (void)vfprintf(err_file, fmt, ap);
1588 (void)fprintf(err_file, "\n");
1589 (void)fflush(err_file);
1590 if (err_file == stderr)
1598 * Produce a Fatal error message. If jobs are running, waits for them
1609 Fatal(const char *fmt, ...)
1617 (void)fflush(stdout);
1618 (void)vfprintf(stderr, fmt, ap);
1620 (void)fprintf(stderr, "\n");
1621 (void)fflush(stderr);
1623 PrintOnError(NULL, NULL);
1625 if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1627 Trace_Log(MAKEERROR, 0);
1628 exit(2); /* Not 1 so -q can distinguish error */
1633 * Major exception once jobs are being created. Kills all jobs, prints
1634 * a message and exits.
1640 * All children are killed indiscriminately and the program Lib_Exits
1644 Punt(const char *fmt, ...)
1649 (void)fflush(stdout);
1650 (void)fprintf(stderr, "%s: ", progname);
1651 (void)vfprintf(stderr, fmt, ap);
1653 (void)fprintf(stderr, "\n");
1654 (void)fflush(stderr);
1656 PrintOnError(NULL, NULL);
1663 * Exit without giving a message.
1678 Trace_Log(MAKEERROR, 0);
1679 exit(2); /* Not 1, so -q can distinguish error */
1684 * Called when aborting due to errors in child shell to signal
1695 /* number of errors encountered in Make_Make */
1697 Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1702 * Remove a file carefully, avoiding directories.
1705 eunlink(const char *file)
1709 if (lstat(file, &st) == -1)
1712 if (S_ISDIR(st.st_mode)) {
1716 return unlink(file);
1721 * Print why exec failed, avoiding stdio.
1724 execError(const char *af, const char *av)
1728 struct iovec iov[8];
1730 (void)(iov[i].iov_base = UNCONST(s), \
1731 iov[i].iov_len = strlen(iov[i].iov_base), \
1734 #define IOADD(s) (void)write(2, s, strlen(s))
1742 IOADD(") failed (");
1743 IOADD(strerror(errno));
1747 while (writev(2, iov, 8) == -1 && errno == EAGAIN)
1754 * exit with usage message
1759 (void)fprintf(stderr,
1760 "usage: %s [-BeikNnqrstWX] \n\
1761 [-C directory] [-D variable] [-d flags] [-f makefile]\n\
1762 [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1763 [-V variable] [variable=value] [target ...]\n", progname);
1769 PrintAddr(void *a, void *b)
1771 printf("%lx ", (unsigned long) a);
1778 PrintOnError(GNode *gn, const char *s)
1780 static GNode *en = NULL;
1787 printf("\n%s: stopped in %s\n", progname, curdir);
1790 return; /* we've been here! */
1793 * We can print this even if there is no .ERROR target.
1795 Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL, 0);
1797 strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1799 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1806 * Finally, see if there is a .ERROR target, and run it if so.
1808 en = Targ_FindNode(".ERROR", TARG_NOCREATE);
1810 en->type |= OP_SPECIAL;
1811 Compat_Make(en, en);
1816 Main_ExportMAKEFLAGS(Boolean first)
1818 static int once = 1;
1826 strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1828 s = Var_Subst(NULL, tmp, VAR_CMD, 0);
1831 setenv("MAKEFLAGS", s, 1);
1833 setenv("MAKE", s, 1);
1841 static char *tmpdir = NULL;
1847 * Honor $TMPDIR but only if it is valid.
1848 * Ensure it ends with /.
1850 tmpdir = Var_Subst(NULL, "${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL, 0);
1851 if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
1853 tmpdir = bmake_strdup(_PATH_TMP);
1860 * Create and open a temp file using "pattern".
1861 * If "fnamep" is provided set it to a copy of the filename created.
1862 * Otherwise unlink the file once open.
1865 mkTempFile(const char *pattern, char **fnamep)
1867 static char *tmpdir = NULL;
1868 char tfile[MAXPATHLEN];
1874 tmpdir = getTmpdir();
1875 if (pattern[0] == '/') {
1876 snprintf(tfile, sizeof(tfile), "%s", pattern);
1878 snprintf(tfile, sizeof(tfile), "%s%s", tmpdir, pattern);
1880 if ((fd = mkstemp(tfile)) < 0)
1881 Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
1883 *fnamep = bmake_strdup(tfile);
1885 unlink(tfile); /* we just want the descriptor */
1892 * Return a Boolean based on setting of a knob.
1894 * If the knob is not set, the supplied default is the return value.
1895 * If set, anything that looks or smells like "No", "False", "Off", "0" etc,
1896 * is FALSE, otherwise TRUE.
1899 getBoolean(const char *name, Boolean bf)
1904 if (snprintf(tmp, sizeof(tmp), "${%s:tl}", name) < (int)(sizeof(tmp))) {
1905 cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1909 case '\0': /* not set - the default wins */