1 /* $NetBSD: main.c,v 1.174 2009/09/09 17:09:49 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.174 2009/09/09 17:09:49 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.174 2009/09/09 17:09:49 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>
120 #include <sys/signal.h>
121 #include <sys/stat.h>
123 #include <sys/utsname.h>
125 #include <sys/wait.h>
138 #include "pathnames.h"
146 #define DEFMAXLOCAL DEFMAXJOBS
147 #endif /* DEFMAXLOCAL */
149 Lst create
; /* Targets to be made */
150 time_t now
; /* Time at start of make */
151 GNode
*DEFAULT
; /* .DEFAULT node */
152 Boolean allPrecious
; /* .PRECIOUS given on line by itself */
154 static Boolean noBuiltins
; /* -r flag */
155 static Lst makefiles
; /* ordered list of makefiles to read */
156 static Boolean printVars
; /* print value of one or more vars */
157 static Lst variables
; /* list of variables to print */
158 int maxJobs
; /* -j argument */
159 static int maxJobTokens
; /* -j argument */
160 Boolean compatMake
; /* -B argument */
161 int debug
; /* -d argument */
162 Boolean noExecute
; /* -n flag */
163 Boolean noRecursiveExecute
; /* -N flag */
164 Boolean keepgoing
; /* -k flag */
165 Boolean queryFlag
; /* -q flag */
166 Boolean touchFlag
; /* -t flag */
167 Boolean ignoreErrors
; /* -i flag */
168 Boolean beSilent
; /* -s flag */
169 Boolean oldVars
; /* variable substitution style */
170 Boolean checkEnvFirst
; /* -e flag */
171 Boolean parseWarnFatal
; /* -W flag */
172 Boolean jobServer
; /* -J flag */
173 static int jp_0
= -1, jp_1
= -1; /* ends of parent job pipe */
174 Boolean varNoExportEnv
; /* -X flag */
175 Boolean doing_depend
; /* Set while reading .depend */
176 static Boolean jobsRunning
; /* TRUE if the jobs might be running */
177 static const char * tracefile
;
178 static char * Check_Cwd_av(int, char **, int);
179 static void MainParseArgs(int, char **);
180 static int ReadMakefile(const void *, const void *);
181 static void usage(void);
183 static Boolean ignorePWD
; /* if we use -C, PWD is meaningless */
184 static char curdir
[MAXPATHLEN
+ 1]; /* startup directory */
185 static char objdir
[MAXPATHLEN
+ 1]; /* where we chdir'ed to */
186 char *progname
; /* the program name */
188 Boolean forceJobs
= FALSE
;
190 extern Lst parseIncPath
;
193 parse_debug_options(const char *argvalue
)
200 for (modules
= argvalue
; *modules
; ++modules
) {
218 debug
|= DEBUG_ERROR
;
224 if (modules
[1] == '1') {
225 debug
|= DEBUG_GRAPH1
;
228 else if (modules
[1] == '2') {
229 debug
|= DEBUG_GRAPH2
;
232 else if (modules
[1] == '3') {
233 debug
|= DEBUG_GRAPH3
;
247 debug
|= DEBUG_SCRIPT
;
250 debug
|= DEBUG_PARSE
;
262 debug
|= DEBUG_SHELL
;
265 if (debug_file
!= stdout
&& debug_file
!= stderr
)
267 if (*++modules
== '+')
271 if (strcmp(modules
, "stdout") == 0) {
275 if (strcmp(modules
, "stderr") == 0) {
279 len
= strlen(modules
);
280 fname
= malloc(len
+ 20);
281 memcpy(fname
, modules
, len
+ 1);
282 /* Let the filename be modified by the pid */
283 if (strcmp(fname
+ len
- 3, ".%d") == 0)
284 snprintf(fname
+ len
- 2, 20, "%d", getpid());
285 debug_file
= fopen(fname
, mode
);
287 fprintf(stderr
, "Cannot open debug file %s\n",
294 (void)fprintf(stderr
,
295 "%s: illegal argument to d option -- %c\n",
302 * Make the debug_file unbuffered, and make
303 * stdout line buffered (unless debugfile == stdout).
305 setvbuf(debug_file
, NULL
, _IONBF
, 0);
306 if (debug_file
!= stdout
) {
307 setvbuf(stdout
, NULL
, _IOLBF
, 0);
313 * Parse a given argument vector. Called from main() and from
314 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
316 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
322 * Various global and local flags will be set depending on the flags
326 MainParseArgs(int argc
, char **argv
)
332 const char *getopt_def
;
334 Boolean inOption
, dashDash
= FALSE
;
335 char found_path
[MAXPATHLEN
+ 1]; /* for searching for sys.mk */
337 #define OPTFLAGS "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrst"
338 /* Can't actually use getopt(3) because rescanning is not portable */
340 getopt_def
= OPTFLAGS
;
358 if (c
!= '-' || dashDash
)
363 /* '-' found at some earlier point */
364 getopt_spec
= strchr(getopt_def
, c
);
365 if(c
!= '\0' && getopt_spec
!= NULL
&& getopt_spec
[1] == ':') {
366 /* -<something> found, and <something> should have an arg */
370 if(*argvalue
== '\0') {
386 Var_Append(MAKEFLAGS
, "-B", VAR_GLOBAL
);
389 if (chdir(argvalue
) == -1) {
390 (void)fprintf(stderr
,
391 "%s: chdir %s: %s\n",
396 if (getcwd(curdir
, MAXPATHLEN
) == NULL
) {
397 (void)fprintf(stderr
, "%s: %s.\n", progname
, strerror(errno
));
403 if (argvalue
== NULL
|| argvalue
[0] == 0) goto noarg
;
404 Var_Set(argvalue
, "1", VAR_GLOBAL
, 0);
405 Var_Append(MAKEFLAGS
, "-D", VAR_GLOBAL
);
406 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
409 if (argvalue
== NULL
) goto noarg
;
410 Parse_AddIncludeDir(argvalue
);
411 Var_Append(MAKEFLAGS
, "-I", VAR_GLOBAL
);
412 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
415 if (argvalue
== NULL
) goto noarg
;
416 if (sscanf(argvalue
, "%d,%d", &jp_0
, &jp_1
) != 2) {
417 (void)fprintf(stderr
,
418 "%s: internal error -- J option malformed (%s)\n",
422 if ((fcntl(jp_0
, F_GETFD
, 0) < 0) ||
423 (fcntl(jp_1
, F_GETFD
, 0) < 0)) {
425 (void)fprintf(stderr
,
426 "%s: ###### warning -- J descriptors were closed!\n",
434 Var_Append(MAKEFLAGS
, "-J", VAR_GLOBAL
);
435 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
441 noRecursiveExecute
= TRUE
;
442 Var_Append(MAKEFLAGS
, "-N", VAR_GLOBAL
);
446 Var_Append(MAKEFLAGS
, "-S", VAR_GLOBAL
);
449 if (argvalue
== NULL
) goto noarg
;
450 tracefile
= bmake_strdup(argvalue
);
451 Var_Append(MAKEFLAGS
, "-T", VAR_GLOBAL
);
452 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
455 if (argvalue
== NULL
) goto noarg
;
457 (void)Lst_AtEnd(variables
, argvalue
);
458 Var_Append(MAKEFLAGS
, "-V", VAR_GLOBAL
);
459 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
462 parseWarnFatal
= TRUE
;
465 varNoExportEnv
= TRUE
;
466 Var_Append(MAKEFLAGS
, "-X", VAR_GLOBAL
);
469 if (argvalue
== NULL
) goto noarg
;
470 /* If '-d-opts' don't pass to children */
471 if (argvalue
[0] == '-')
474 Var_Append(MAKEFLAGS
, "-d", VAR_GLOBAL
);
475 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
477 parse_debug_options(argvalue
);
480 checkEnvFirst
= TRUE
;
481 Var_Append(MAKEFLAGS
, "-e", VAR_GLOBAL
);
484 if (argvalue
== NULL
) goto noarg
;
485 (void)Lst_AtEnd(makefiles
, argvalue
);
489 Var_Append(MAKEFLAGS
, "-i", VAR_GLOBAL
);
492 if (argvalue
== NULL
) goto noarg
;
494 maxJobs
= strtol(argvalue
, &p
, 0);
495 if (*p
!= '\0' || maxJobs
< 1) {
496 (void)fprintf(stderr
, "%s: illegal argument to -j -- must be positive integer!\n",
500 Var_Append(MAKEFLAGS
, "-j", VAR_GLOBAL
);
501 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
502 maxJobTokens
= maxJobs
;
506 Var_Append(MAKEFLAGS
, "-k", VAR_GLOBAL
);
509 if (argvalue
== NULL
) goto noarg
;
510 /* look for magic parent directory search string */
511 if (strncmp(".../", argvalue
, 4) == 0) {
512 if (!Dir_FindHereOrAbove(curdir
, argvalue
+4,
513 found_path
, sizeof(found_path
)))
514 break; /* nothing doing */
515 (void)Dir_AddDir(sysIncPath
, found_path
);
517 (void)Dir_AddDir(sysIncPath
, argvalue
);
519 Var_Append(MAKEFLAGS
, "-m", VAR_GLOBAL
);
520 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
524 Var_Append(MAKEFLAGS
, "-n", VAR_GLOBAL
);
528 /* Kind of nonsensical, wot? */
529 Var_Append(MAKEFLAGS
, "-q", VAR_GLOBAL
);
533 Var_Append(MAKEFLAGS
, "-r", VAR_GLOBAL
);
537 Var_Append(MAKEFLAGS
, "-s", VAR_GLOBAL
);
541 Var_Append(MAKEFLAGS
, "-t", VAR_GLOBAL
);
557 * See if the rest of the arguments are variable assignments and
558 * perform them if so. Else take them to be targets and stuff them
559 * on the end of the "create" list.
561 for (; argc
> 1; ++argv
, --argc
)
562 if (Parse_IsVar(argv
[1])) {
563 Parse_DoVar(argv
[1], VAR_CMD
);
566 Punt("illegal (null) argument.");
567 if (*argv
[1] == '-' && !dashDash
)
569 (void)Lst_AtEnd(create
, bmake_strdup(argv
[1]));
574 (void)fprintf(stderr
, "%s: option requires an argument -- %c\n",
580 * Main_ParseArgLine --
581 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
582 * is encountered and by main() when reading the .MAKEFLAGS envariable.
583 * Takes a line of arguments and breaks it into its
584 * component words and passes those words and the number of them to the
585 * MainParseArgs function.
586 * The line should have all its leading whitespace removed.
589 * line Line to fracture
595 * Only those that come from the various arguments.
598 Main_ParseArgLine(const char *line
)
600 char **argv
; /* Manufactured argument vector */
601 int argc
; /* Number of arguments in argv */
602 char *args
; /* Space used by the args */
604 char *argv0
= Var_Value(".MAKE", VAR_GLOBAL
, &p1
);
609 for (; *line
== ' '; ++line
)
614 buf
= bmake_malloc(len
= strlen(line
) + strlen(argv0
) + 2);
615 (void)snprintf(buf
, len
, "%s %s", argv0
, line
);
619 argv
= brk_string(buf
, &argc
, TRUE
, &args
);
621 Error("Unterminated quoted string [%s]", buf
);
626 MainParseArgs(argc
, argv
);
633 Main_SetObjdir(const char *path
)
637 char buf
[MAXPATHLEN
+ 1];
640 /* expand variable substitutions */
641 if (strchr(path
, '$') != 0) {
642 snprintf(buf
, MAXPATHLEN
, "%s", path
);
643 path
= p
= Var_Subst(NULL
, buf
, VAR_GLOBAL
, 0);
646 if (path
[0] != '/') {
647 snprintf(buf
, MAXPATHLEN
, "%s/%s", curdir
, path
);
651 /* look for the directory and try to chdir there */
652 if (stat(path
, &sb
) == 0 && S_ISDIR(sb
.st_mode
)) {
654 (void)fprintf(stderr
, "make warning: %s: %s.\n",
655 path
, strerror(errno
));
657 strncpy(objdir
, path
, MAXPATHLEN
);
658 Var_Set(".OBJDIR", objdir
, VAR_GLOBAL
, 0);
659 setenv("PWD", objdir
, 1);
671 * ReadAllMakefiles --
672 * wrapper around ReadMakefile() to read all.
675 * TRUE if ok, FALSE on error
678 ReadAllMakefiles(const void *p
, const void *q
)
680 return (ReadMakefile(p
, q
) == 0);
688 char dir
[MAXPATHLEN
];
689 char str
[2 * MAXPATHLEN
];
691 if (getcwd(dir
, sizeof(dir
)) == NULL
)
693 len
= snprintf(str
, sizeof(str
), "%s: Working in: %s\n", progname
, dir
);
695 (void)write(STDERR_FILENO
, str
, (size_t)len
);
701 * The main function, for obvious reasons. Initializes variables
702 * and a few modules, then parses the arguments give it in the
703 * environment and on the command line. Reads the system makefile
704 * followed by either Makefile, makefile or the file given by the
705 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
706 * flags it has received by then uses either the Make or the Compat
707 * module to create the initial list of targets.
710 * If -q was given, exits -1 if anything was out-of-date. Else it exits
714 * The program exits when done. Targets are created. etc. etc. etc.
717 main(int argc
, char **argv
)
719 Lst targs
; /* target nodes to create -- passed to Make_Init */
720 Boolean outOfDate
= FALSE
; /* FALSE if all targets up to date */
722 char *p1
, *path
, *pwd
;
723 char mdpath
[MAXPATHLEN
];
724 char *machine
= getenv("MACHINE");
725 const char *machine_arch
= getenv("MACHINE_ARCH");
726 char *syspath
= getenv("MAKESYSPATH");
727 Lst sysMkPath
; /* Path of sys.mk */
728 char *cp
= NULL
, *start
;
729 /* avoid faults on read-only strings */
730 static char defsyspath
[] = _PATH_DEFSYSPATH
;
731 char found_path
[MAXPATHLEN
+ 1]; /* for searching for sys.mk */
732 struct timeval rightnow
; /* to initialize random seed */
734 struct utsname utsname
;
737 /* default to writing debug to stderr */
741 (void)signal(SIGINFO
, siginfo
);
744 * Set the seed to produce a different random sequence
745 * on each program execution.
747 gettimeofday(&rightnow
, NULL
);
748 srandom(rightnow
.tv_sec
+ rightnow
.tv_usec
);
750 if ((progname
= strrchr(argv
[0], '/')) != NULL
)
756 * get rid of resource limit on file descriptors
760 if (getrlimit(RLIMIT_NOFILE
, &rl
) != -1 &&
761 rl
.rlim_cur
!= rl
.rlim_max
) {
762 rl
.rlim_cur
= rl
.rlim_max
;
763 (void)setrlimit(RLIMIT_NOFILE
, &rl
);
769 * Get the name of this type of MACHINE from utsname
770 * so we can share an executable for similar machines.
771 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
773 * Note that both MACHINE and MACHINE_ARCH are decided at
778 if (uname(&utsname
) == -1) {
779 (void)fprintf(stderr
, "%s: uname failed (%s).\n", progname
,
783 machine
= utsname
.machine
;
786 machine
= MAKE_MACHINE
;
795 #ifdef MAKE_MACHINE_ARCH
796 machine_arch
= MAKE_MACHINE_ARCH
;
798 machine_arch
= "unknown";
801 machine_arch
= MACHINE_ARCH
;
806 * Just in case MAKEOBJDIR wants us to do something tricky.
808 Var_Init(); /* Initialize the lists of variables for
809 * parsing arguments */
810 Var_Set("MACHINE", machine
, VAR_GLOBAL
, 0);
811 Var_Set("MACHINE_ARCH", machine_arch
, VAR_GLOBAL
, 0);
813 Var_Set("MAKE_VERSION", MAKE_VERSION
, VAR_GLOBAL
, 0);
815 Var_Set(".newline", "\n", VAR_GLOBAL
, 0); /* handy for :@ loops */
817 create
= Lst_Init(FALSE
);
818 makefiles
= Lst_Init(FALSE
);
820 variables
= Lst_Init(FALSE
);
821 beSilent
= FALSE
; /* Print commands as executed */
822 ignoreErrors
= FALSE
; /* Pay attention to non-zero returns */
823 noExecute
= FALSE
; /* Execute all commands */
824 noRecursiveExecute
= FALSE
; /* Execute all .MAKE targets */
825 keepgoing
= FALSE
; /* Stop on error */
826 allPrecious
= FALSE
; /* Remove targets when interrupted */
827 queryFlag
= FALSE
; /* This is not just a check-run */
828 noBuiltins
= FALSE
; /* Read the built-in rules */
829 touchFlag
= FALSE
; /* Actually update targets */
830 debug
= 0; /* No debug verbosity, please. */
833 maxJobs
= DEFMAXLOCAL
; /* Set default local max concurrency */
834 maxJobTokens
= maxJobs
;
835 compatMake
= FALSE
; /* No compat mode */
839 * Initialize the parsing, directory and variable modules to prepare
840 * for the reading of inclusion paths and variable settings on the
845 * Initialize various variables.
846 * MAKE also gets this name, for compatibility
847 * .MAKEFLAGS gets set to the empty string just in case.
848 * MFLAGS also gets initialized empty, for compatibility.
851 Var_Set("MAKE", argv
[0], VAR_GLOBAL
, 0);
852 Var_Set(".MAKE", argv
[0], VAR_GLOBAL
, 0);
853 Var_Set(MAKEFLAGS
, "", VAR_GLOBAL
, 0);
854 Var_Set(MAKEOVERRIDES
, "", VAR_GLOBAL
, 0);
855 Var_Set("MFLAGS", "", VAR_GLOBAL
, 0);
856 Var_Set(".ALLTARGETS", "", VAR_GLOBAL
, 0);
859 * Set some other useful macros
865 if (!(ep
= getenv(MAKE_LEVEL
))) {
868 Var_Set(MAKE_LEVEL
, ep
, VAR_GLOBAL
, 0);
869 snprintf(tmp
, sizeof(tmp
), "%u", getpid());
870 Var_Set(".MAKE.PID", tmp
, VAR_GLOBAL
, 0);
871 snprintf(tmp
, sizeof(tmp
), "%u", getppid());
872 Var_Set(".MAKE.PPID", tmp
, VAR_GLOBAL
, 0);
877 * First snag any flags out of the MAKE environment variable.
878 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
879 * in a different format).
882 Main_ParseArgLine(getenv("MAKEFLAGS"));
884 Main_ParseArgLine(getenv("MAKE"));
888 * Find where we are (now).
889 * We take care of PWD for the automounter below...
891 if (getcwd(curdir
, MAXPATHLEN
) == NULL
) {
892 (void)fprintf(stderr
, "%s: %s.\n", progname
, strerror(errno
));
896 MainParseArgs(argc
, argv
);
899 * Verify that cwd is sane.
901 if (stat(curdir
, &sa
) == -1) {
902 (void)fprintf(stderr
, "%s: %s: %s.\n",
903 progname
, curdir
, strerror(errno
));
908 * All this code is so that we know where we are when we start up
909 * on a different machine with pmake.
910 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
911 * since the value of curdir can vary depending on how we got
912 * here. Ie sitting at a shell prompt (shell that provides $PWD)
913 * or via subdir.mk in which case its likely a shell which does
915 * So, to stop it breaking this case only, we ignore PWD if
916 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
919 (pwd
= getenv("PWD")) != NULL
&&
920 getenv("MAKEOBJDIRPREFIX") == NULL
) {
921 const char *makeobjdir
= getenv("MAKEOBJDIR");
923 if (makeobjdir
== NULL
|| !strchr(makeobjdir
, '$')) {
924 if (stat(pwd
, &sb
) == 0 && sa
.st_ino
== sb
.st_ino
&&
925 sa
.st_dev
== sb
.st_dev
)
926 (void)strncpy(curdir
, pwd
, MAXPATHLEN
);
929 Var_Set(".CURDIR", curdir
, VAR_GLOBAL
, 0);
932 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
933 * MAKEOBJDIR is set in the environment, try only that value
934 * and fall back to .CURDIR if it does not exist.
936 * Otherwise, try _PATH_OBJDIR.MACHINE, _PATH_OBJDIR, and
937 * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
938 * of these paths exist, just use .CURDIR.
941 (void)Main_SetObjdir(curdir
);
943 if ((path
= getenv("MAKEOBJDIRPREFIX")) != NULL
) {
944 (void)snprintf(mdpath
, MAXPATHLEN
, "%s%s", path
, curdir
);
945 (void)Main_SetObjdir(mdpath
);
946 } else if ((path
= getenv("MAKEOBJDIR")) != NULL
) {
947 (void)Main_SetObjdir(path
);
949 (void)snprintf(mdpath
, MAXPATHLEN
, "%s.%s", _PATH_OBJDIR
, machine
);
950 if (!Main_SetObjdir(mdpath
) && !Main_SetObjdir(_PATH_OBJDIR
)) {
951 (void)snprintf(mdpath
, MAXPATHLEN
, "%s%s",
952 _PATH_OBJDIRPREFIX
, curdir
);
953 (void)Main_SetObjdir(mdpath
);
958 * Be compatible if user did not specify -j and did not explicitly
959 * turned compatibility on
961 if (!compatMake
&& !forceJobs
) {
966 * Initialize archive, target and suffix modules in preparation for
967 * parsing the makefile(s)
972 Trace_Init(tracefile
);
977 Trace_Log(MAKESTART
, NULL
);
980 * Set up the .TARGETS variable to contain the list of targets to be
981 * created. If none specified, make the variable empty -- the parser
982 * will fill the thing in with the default or .MAIN target.
984 if (!Lst_IsEmpty(create
)) {
987 for (ln
= Lst_First(create
); ln
!= NULL
;
989 char *name
= (char *)Lst_Datum(ln
);
991 Var_Append(".TARGETS", name
, VAR_GLOBAL
);
994 Var_Set(".TARGETS", "", VAR_GLOBAL
, 0);
998 * If no user-supplied system path was given (through the -m option)
999 * add the directories from the DEFSYSPATH (more than one may be given
1000 * as dir1:...:dirn) to the system include path.
1002 if (syspath
== NULL
|| *syspath
== '\0')
1003 syspath
= defsyspath
;
1005 syspath
= bmake_strdup(syspath
);
1007 for (start
= syspath
; *start
!= '\0'; start
= cp
) {
1008 for (cp
= start
; *cp
!= '\0' && *cp
!= ':'; cp
++)
1013 /* look for magic parent directory search string */
1014 if (strncmp(".../", start
, 4) != 0) {
1015 (void)Dir_AddDir(defIncPath
, start
);
1017 if (Dir_FindHereOrAbove(curdir
, start
+4,
1018 found_path
, sizeof(found_path
))) {
1019 (void)Dir_AddDir(defIncPath
, found_path
);
1023 if (syspath
!= defsyspath
)
1027 * Read in the built-in rules first, followed by the specified
1028 * makefile, if it was (makefile != NULL), or the default
1029 * makefile and Makefile, in that order, if it wasn't.
1034 sysMkPath
= Lst_Init(FALSE
);
1035 Dir_Expand(_PATH_DEFSYSMK
,
1036 Lst_IsEmpty(sysIncPath
) ? defIncPath
: sysIncPath
,
1038 if (Lst_IsEmpty(sysMkPath
))
1039 Fatal("%s: no system rules (%s).", progname
,
1041 ln
= Lst_Find(sysMkPath
, NULL
, ReadMakefile
);
1043 Fatal("%s: cannot open %s.", progname
,
1044 (char *)Lst_Datum(ln
));
1047 if (!Lst_IsEmpty(makefiles
)) {
1050 ln
= Lst_Find(makefiles
, NULL
, ReadAllMakefiles
);
1052 Fatal("%s: cannot open %s.", progname
,
1053 (char *)Lst_Datum(ln
));
1054 } else if (ReadMakefile("makefile", NULL
) != 0)
1055 (void)ReadMakefile("Makefile", NULL
);
1057 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1058 if (!noBuiltins
|| !printVars
) {
1059 doing_depend
= TRUE
;
1060 (void)ReadMakefile(".depend", NULL
);
1061 doing_depend
= FALSE
;
1064 Var_Append("MFLAGS", Var_Value(MAKEFLAGS
, VAR_GLOBAL
, &p1
), VAR_GLOBAL
);
1069 Job_ServerStart(maxJobTokens
, jp_0
, jp_1
);
1071 fprintf(debug_file
, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1072 jp_0
, jp_1
, maxJobs
, maxJobTokens
, compatMake
);
1074 Main_ExportMAKEFLAGS(TRUE
); /* initial export */
1076 Check_Cwd_av(0, NULL
, 0); /* initialize it */
1080 * For compatibility, look at the directories in the VPATH variable
1081 * and add them to the search path, if the variable is defined. The
1082 * variable's value is in the same format as the PATH envariable, i.e.
1083 * <directory>:<directory>:<directory>...
1085 if (Var_Exists("VPATH", VAR_CMD
)) {
1088 * GCC stores string constants in read-only memory, but
1089 * Var_Subst will want to write this thing, so store it
1092 static char VPATH
[] = "${VPATH}";
1094 vpath
= Var_Subst(NULL
, VPATH
, VAR_CMD
, FALSE
);
1097 /* skip to end of directory */
1098 for (cp
= path
; *cp
!= ':' && *cp
!= '\0'; cp
++)
1100 /* Save terminator character so know when to stop */
1103 /* Add directory to search path */
1104 (void)Dir_AddDir(dirSearchPath
, path
);
1107 } while (savec
== ':');
1112 * Now that all search paths have been read for suffixes et al, it's
1113 * time to add the default search path to their lists...
1118 * Propagate attributes through :: dependency lists.
1122 /* print the initial graph, if the user requested it */
1126 /* print the values of any variables requested by the user */
1130 for (ln
= Lst_First(variables
); ln
!= NULL
;
1131 ln
= Lst_Succ(ln
)) {
1132 char *var
= (char *)Lst_Datum(ln
);
1135 if (strchr(var
, '$')) {
1136 value
= p1
= Var_Subst(NULL
, var
, VAR_GLOBAL
, 0);
1138 value
= Var_Value(var
, VAR_GLOBAL
, &p1
);
1140 printf("%s\n", value
? value
: "");
1146 * Have now read the entire graph and need to make a list of
1147 * targets to create. If none was given on the command line,
1148 * we consult the parsing module to find the main target(s)
1151 if (Lst_IsEmpty(create
))
1152 targs
= Parse_MainName();
1154 targs
= Targ_FindList(create
, TARG_CREATE
);
1158 * Initialize job module before traversing the graph
1159 * now that any .BEGIN and .END targets have been read.
1160 * This is done only if the -q flag wasn't given
1161 * (to prevent the .BEGIN from being executed should
1169 /* Traverse the graph, checking on all the targets */
1170 outOfDate
= Make_Run(targs
);
1173 * Compat_Init will take care of creating all the
1174 * targets as well as initializing the module.
1181 Lst_Destroy(targs
, NULL
);
1182 Lst_Destroy(variables
, NULL
);
1183 Lst_Destroy(makefiles
, NULL
);
1184 Lst_Destroy(create
, (FreeProc
*)free
);
1187 /* print the graph now it's been processed if the user requested it */
1191 Trace_Log(MAKEEND
, 0);
1202 return outOfDate
? 1 : 0;
1207 * Open and parse the given makefile.
1210 * 0 if ok. -1 if couldn't open file.
1216 ReadMakefile(const void *p
, const void *q __unused
)
1218 const char *fname
= p
; /* makefile to read */
1220 size_t len
= MAXPATHLEN
;
1221 char *name
, *path
= bmake_malloc(len
);
1224 if (!strcmp(fname
, "-")) {
1225 Parse_File("(stdin)", dup(fileno(stdin
)));
1226 Var_Set("MAKEFILE", "", VAR_GLOBAL
, 0);
1228 setMAKEFILE
= strcmp(fname
, ".depend");
1230 /* if we've chdir'd, rebuild the path name */
1231 if (strcmp(curdir
, objdir
) && *fname
!= '/') {
1232 size_t plen
= strlen(curdir
) + strlen(fname
) + 2;
1234 path
= bmake_realloc(path
, len
= 2 * plen
);
1236 (void)snprintf(path
, len
, "%s/%s", curdir
, fname
);
1237 fd
= open(path
, O_RDONLY
);
1243 /* If curdir failed, try objdir (ala .depend) */
1244 plen
= strlen(objdir
) + strlen(fname
) + 2;
1246 path
= bmake_realloc(path
, len
= 2 * plen
);
1247 (void)snprintf(path
, len
, "%s/%s", objdir
, fname
);
1248 fd
= open(path
, O_RDONLY
);
1254 fd
= open(fname
, O_RDONLY
);
1258 /* look in -I and system include directories. */
1259 name
= Dir_FindFile(fname
, parseIncPath
);
1261 name
= Dir_FindFile(fname
,
1262 Lst_IsEmpty(sysIncPath
) ? defIncPath
: sysIncPath
);
1263 if (!name
|| (fd
= open(name
, O_RDONLY
)) == -1) {
1271 * set the MAKEFILE variable desired by System V fans -- the
1272 * placement of the setting here means it gets set to the last
1273 * makefile specified, as it is set by SysV make.
1277 Var_Set("MAKEFILE", fname
, VAR_GLOBAL
, 0);
1278 Parse_File(fname
, fd
);
1286 * If MAKEOBJDIRPREFIX is in use, make ends up not in .CURDIR
1287 * in situations that would not arrise with ./obj (links or not).
1288 * This tends to break things like:
1293 * This function spots when ${.MAKE:T} or ${.MAKE} is a command (as
1294 * opposed to an argument) in a command line and if so returns
1295 * ${.CURDIR} so caller can chdir() so that the assumptions made by
1296 * the Makefile hold true.
1298 * If ${.MAKE} does not contain any '/', then ${.MAKE:T} is skipped.
1300 * The chdir() only happens in the child process, and does nothing if
1301 * MAKEOBJDIRPREFIX and MAKEOBJDIR are not in the environment so it
1302 * should not break anything. Also if NOCHECKMAKECHDIR is set we
1303 * do nothing - to ensure historic semantics can be retained.
1305 static int Check_Cwd_Off
= 0;
1308 Check_Cwd_av(int ac
, char **av
, int copy
)
1310 static char *make
[4];
1311 static char *cur_dir
= NULL
;
1314 int is_cmd
, next_cmd
;
1318 if (Check_Cwd_Off
) {
1320 fprintf(debug_file
, "check_cwd: check is off.\n");
1324 if (make
[0] == NULL
) {
1325 if (Var_Exists("NOCHECKMAKECHDIR", VAR_GLOBAL
)) {
1328 fprintf(debug_file
, "check_cwd: turning check off.\n");
1332 make
[1] = Var_Value(".MAKE", VAR_GLOBAL
, &cp
);
1333 if ((make
[0] = strrchr(make
[1], '/')) == NULL
) {
1339 cur_dir
= Var_Value(".CURDIR", VAR_GLOBAL
, &cp
);
1341 if (ac
== 0 || av
== NULL
) {
1343 fprintf(debug_file
, "check_cwd: empty command.\n");
1344 return NULL
; /* initialization only */
1347 if (getenv("MAKEOBJDIR") == NULL
&&
1348 getenv("MAKEOBJDIRPREFIX") == NULL
) {
1350 fprintf(debug_file
, "check_cwd: no obj dirs.\n");
1356 for (i
= 0; i
< ac
; ++i
) {
1360 cp
= &(av
[i
])[n
- 1];
1361 if (strspn(av
[i
], "|&;") == (size_t)n
) {
1364 } else if (*cp
== ';' || *cp
== '&' || *cp
== '|' || *cp
== ')') {
1369 } while (*cp
== ';' || *cp
== '&' || *cp
== '|' ||
1370 *cp
== ')' || *cp
== '}') ;
1373 * XXX this should not happen.
1375 fprintf(stderr
, "%s: WARNING: raw arg ends in shell meta '%s'\n",
1382 if (*cp
== ';' || *cp
== '&' || *cp
== '|')
1386 fprintf(debug_file
, "av[%d] == %s '%s'",
1387 i
, (is_cmd
) ? "cmd" : "arg", av
[i
]);
1389 if (*cp
== '(' || *cp
== '{' ||
1390 *cp
== ';' || *cp
== '&' || *cp
== '|') {
1393 } while (*cp
== '(' || *cp
== '{' ||
1394 *cp
== ';' || *cp
== '&' || *cp
== '|');
1400 if (strcmp(cp
, "cd") == 0 || strcmp(cp
, "chdir") == 0) {
1402 fprintf(debug_file
, " == cd, done.\n");
1405 for (mp
= make
; *mp
!= NULL
; ++mp
) {
1407 if (strcmp(cp
, *mp
) == 0) {
1409 fprintf(debug_file
, " %s == '%s', chdir(%s)\n",
1416 fprintf(debug_file
, "\n");
1422 Check_Cwd_Cmd(const char *cmd
)
1432 av
= brk_string(cmd
, &ac
, TRUE
, &bp
);
1434 fprintf(debug_file
, "splitting: '%s' -> %d words\n",
1441 cp
= Check_Cwd_av(ac
, av
, 1);
1450 Check_Cwd(const char **argv
)
1458 for (ac
= 0; argv
[ac
] != NULL
; ++ac
)
1460 if (ac
== 3 && *argv
[1] == '-') {
1461 cp
= Check_Cwd_Cmd(argv
[2]);
1463 cp
= Check_Cwd_av(ac
, UNCONST(argv
), 0);
1472 * Execute the command in cmd, and return the output of that command
1476 * A string containing the output of the command, or the empty string
1477 * If errnum is not NULL, it contains the reason for the command failure
1480 * The string must be freed by the caller.
1483 Cmd_Exec(const char *cmd
, const char **errnum
)
1485 const char *args
[4]; /* Args for invoking the shell */
1486 int fds
[2]; /* Pipe streams */
1487 int cpid
; /* Child PID */
1488 int pid
; /* PID from wait() */
1489 char *res
; /* result */
1490 int status
; /* command exit status */
1491 Buffer buf
; /* buffer to store the result */
1501 * Set up arguments for shell
1503 args
[0] = shellName
;
1509 * Open a pipe for fetching its output
1511 if (pipe(fds
) == -1) {
1512 *errnum
= "Couldn't create pipe for \"%s\"";
1519 switch (cpid
= vfork()) {
1522 * Close input side of pipe
1524 (void)close(fds
[0]);
1527 * Duplicate the output stream to the shell's output, then
1528 * shut the extra thing down. Note we don't fetch the error
1529 * stream...why not? Why?
1531 (void)dup2(fds
[1], 1);
1532 (void)close(fds
[1]);
1536 (void)execv(shellPath
, UNCONST(args
));
1541 *errnum
= "Couldn't exec \"%s\"";
1546 * No need for the writing half
1548 (void)close(fds
[1]);
1553 char result
[BUFSIZ
];
1554 cc
= read(fds
[0], result
, sizeof(result
));
1556 Buf_AddBytes(&buf
, cc
, result
);
1558 while (cc
> 0 || (cc
== -1 && errno
== EINTR
));
1561 * Close the input side of the pipe.
1563 (void)close(fds
[0]);
1566 * Wait for the process to exit.
1568 while(((pid
= waitpid(cpid
, &status
, 0)) != cpid
) && (pid
>= 0))
1571 cc
= Buf_Size(&buf
);
1572 res
= Buf_Destroy(&buf
, FALSE
);
1575 *errnum
= "Couldn't read shell's output for \"%s\"";
1577 if (WIFSIGNALED(status
))
1578 *errnum
= "\"%s\" exited on a signal";
1579 else if (WEXITSTATUS(status
) != 0)
1580 *errnum
= "\"%s\" returned non-zero status";
1583 * Null-terminate the result, convert newlines to spaces and
1584 * install it in the variable.
1589 if (cc
> 0 && *--cp
== '\n') {
1591 * A final newline is just stripped
1605 res
= bmake_malloc(1);
1612 * Print an error message given its format.
1618 * The message is printed.
1622 Error(const char *fmt
, ...)
1627 err_file
= debug_file
;
1628 if (err_file
== stdout
)
1632 fprintf(err_file
, "%s: ", progname
);
1633 (void)vfprintf(err_file
, fmt
, ap
);
1635 (void)fprintf(err_file
, "\n");
1636 (void)fflush(err_file
);
1637 if (err_file
== stderr
)
1645 * Produce a Fatal error message. If jobs are running, waits for them
1656 Fatal(const char *fmt
, ...)
1664 (void)vfprintf(stderr
, fmt
, ap
);
1666 (void)fprintf(stderr
, "\n");
1667 (void)fflush(stderr
);
1671 if (DEBUG(GRAPH2
) || DEBUG(GRAPH3
))
1673 Trace_Log(MAKEERROR
, 0);
1674 exit(2); /* Not 1 so -q can distinguish error */
1679 * Major exception once jobs are being created. Kills all jobs, prints
1680 * a message and exits.
1686 * All children are killed indiscriminately and the program Lib_Exits
1690 Punt(const char *fmt
, ...)
1695 (void)fprintf(stderr
, "%s: ", progname
);
1696 (void)vfprintf(stderr
, fmt
, ap
);
1698 (void)fprintf(stderr
, "\n");
1699 (void)fflush(stderr
);
1708 * Exit without giving a message.
1723 Trace_Log(MAKEERROR
, 0);
1724 exit(2); /* Not 1, so -q can distinguish error */
1729 * Called when aborting due to errors in child shell to signal
1740 /* number of errors encountered in Make_Make */
1742 Fatal("%d error%s", errors
, errors
== 1 ? "" : "s");
1747 * Remove a file carefully, avoiding directories.
1750 eunlink(const char *file
)
1754 if (lstat(file
, &st
) == -1)
1757 if (S_ISDIR(st
.st_mode
)) {
1761 return unlink(file
);
1766 * Print why exec failed, avoiding stdio.
1769 execError(const char *af
, const char *av
)
1773 struct iovec iov
[8];
1775 (void)(iov[i].iov_base = UNCONST(s), \
1776 iov[i].iov_len = strlen(iov[i].iov_base), \
1779 #define IOADD(void)write(2, s, strlen(s))
1787 IOADD(") failed (");
1788 IOADD(strerror(errno
));
1792 (void)writev(2, iov
, 8);
1798 * exit with usage message
1803 (void)fprintf(stderr
,
1804 "usage: %s [-BeikNnqrstWX] \n\
1805 [-C directory] [-D variable] [-d flags] [-f makefile]\n\
1806 [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1807 [-V variable] [variable=value] [target ...]\n", progname
);
1813 PrintAddr(void *a
, void *b
)
1815 printf("%lx ", (unsigned long) a
);
1822 PrintOnError(const char *s
)
1830 printf("\n%s: stopped in %s\n", progname
, curdir
);
1831 strncpy(tmp
, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1833 cp
= Var_Subst(NULL
, tmp
, VAR_GLOBAL
, 0);
1842 Main_ExportMAKEFLAGS(Boolean first
)
1844 static int once
= 1;
1852 strncpy(tmp
, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1854 s
= Var_Subst(NULL
, tmp
, VAR_CMD
, 0);
1857 setenv("MAKEFLAGS", s
, 1);
1859 setenv("MAKE", s
, 1);