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",
399 if (argvalue
== NULL
|| argvalue
[0] == 0) goto noarg
;
400 Var_Set(argvalue
, "1", VAR_GLOBAL
, 0);
401 Var_Append(MAKEFLAGS
, "-D", VAR_GLOBAL
);
402 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
405 if (argvalue
== NULL
) goto noarg
;
406 Parse_AddIncludeDir(argvalue
);
407 Var_Append(MAKEFLAGS
, "-I", VAR_GLOBAL
);
408 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
411 if (argvalue
== NULL
) goto noarg
;
412 if (sscanf(argvalue
, "%d,%d", &jp_0
, &jp_1
) != 2) {
413 (void)fprintf(stderr
,
414 "%s: internal error -- J option malformed (%s)\n",
418 if ((fcntl(jp_0
, F_GETFD
, 0) < 0) ||
419 (fcntl(jp_1
, F_GETFD
, 0) < 0)) {
421 (void)fprintf(stderr
,
422 "%s: ###### warning -- J descriptors were closed!\n",
430 Var_Append(MAKEFLAGS
, "-J", VAR_GLOBAL
);
431 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
437 noRecursiveExecute
= TRUE
;
438 Var_Append(MAKEFLAGS
, "-N", VAR_GLOBAL
);
442 Var_Append(MAKEFLAGS
, "-S", VAR_GLOBAL
);
445 if (argvalue
== NULL
) goto noarg
;
446 tracefile
= bmake_strdup(argvalue
);
447 Var_Append(MAKEFLAGS
, "-T", VAR_GLOBAL
);
448 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
451 if (argvalue
== NULL
) goto noarg
;
453 (void)Lst_AtEnd(variables
, argvalue
);
454 Var_Append(MAKEFLAGS
, "-V", VAR_GLOBAL
);
455 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
458 parseWarnFatal
= TRUE
;
461 varNoExportEnv
= TRUE
;
462 Var_Append(MAKEFLAGS
, "-X", VAR_GLOBAL
);
465 if (argvalue
== NULL
) goto noarg
;
466 /* If '-d-opts' don't pass to children */
467 if (argvalue
[0] == '-')
470 Var_Append(MAKEFLAGS
, "-d", VAR_GLOBAL
);
471 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
473 parse_debug_options(argvalue
);
476 checkEnvFirst
= TRUE
;
477 Var_Append(MAKEFLAGS
, "-e", VAR_GLOBAL
);
480 if (argvalue
== NULL
) goto noarg
;
481 (void)Lst_AtEnd(makefiles
, argvalue
);
485 Var_Append(MAKEFLAGS
, "-i", VAR_GLOBAL
);
488 if (argvalue
== NULL
) goto noarg
;
490 maxJobs
= strtol(argvalue
, &p
, 0);
491 if (*p
!= '\0' || maxJobs
< 1) {
492 (void)fprintf(stderr
, "%s: illegal argument to -j -- must be positive integer!\n",
496 Var_Append(MAKEFLAGS
, "-j", VAR_GLOBAL
);
497 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
498 maxJobTokens
= maxJobs
;
502 Var_Append(MAKEFLAGS
, "-k", VAR_GLOBAL
);
505 if (argvalue
== NULL
) goto noarg
;
506 /* look for magic parent directory search string */
507 if (strncmp(".../", argvalue
, 4) == 0) {
508 if (!Dir_FindHereOrAbove(curdir
, argvalue
+4,
509 found_path
, sizeof(found_path
)))
510 break; /* nothing doing */
511 (void)Dir_AddDir(sysIncPath
, found_path
);
514 (void)Dir_AddDir(sysIncPath
, argvalue
);
516 Var_Append(MAKEFLAGS
, "-m", VAR_GLOBAL
);
517 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
521 Var_Append(MAKEFLAGS
, "-n", VAR_GLOBAL
);
525 /* Kind of nonsensical, wot? */
526 Var_Append(MAKEFLAGS
, "-q", VAR_GLOBAL
);
530 Var_Append(MAKEFLAGS
, "-r", VAR_GLOBAL
);
534 Var_Append(MAKEFLAGS
, "-s", VAR_GLOBAL
);
538 Var_Append(MAKEFLAGS
, "-t", VAR_GLOBAL
);
554 * See if the rest of the arguments are variable assignments and
555 * perform them if so. Else take them to be targets and stuff them
556 * on the end of the "create" list.
558 for (; argc
> 1; ++argv
, --argc
)
559 if (Parse_IsVar(argv
[1])) {
560 Parse_DoVar(argv
[1], VAR_CMD
);
563 Punt("illegal (null) argument.");
564 if (*argv
[1] == '-' && !dashDash
)
566 (void)Lst_AtEnd(create
, bmake_strdup(argv
[1]));
571 (void)fprintf(stderr
, "%s: option requires an argument -- %c\n",
577 * Main_ParseArgLine --
578 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
579 * is encountered and by main() when reading the .MAKEFLAGS envariable.
580 * Takes a line of arguments and breaks it into its
581 * component words and passes those words and the number of them to the
582 * MainParseArgs function.
583 * The line should have all its leading whitespace removed.
586 * line Line to fracture
592 * Only those that come from the various arguments.
595 Main_ParseArgLine(const char *line
)
597 char **argv
; /* Manufactured argument vector */
598 int argc
; /* Number of arguments in argv */
599 char *args
; /* Space used by the args */
601 char *argv0
= Var_Value(".MAKE", VAR_GLOBAL
, &p1
);
606 for (; *line
== ' '; ++line
)
611 buf
= bmake_malloc(len
= strlen(line
) + strlen(argv0
) + 2);
612 (void)snprintf(buf
, len
, "%s %s", argv0
, line
);
616 argv
= brk_string(buf
, &argc
, TRUE
, &args
);
618 Error("Unterminated quoted string [%s]", buf
);
623 MainParseArgs(argc
, argv
);
630 Main_SetObjdir(const char *path
)
634 char buf
[MAXPATHLEN
+ 1];
637 /* expand variable substitutions */
638 if (strchr(path
, '$') != 0) {
639 snprintf(buf
, MAXPATHLEN
, "%s", path
);
640 path
= p
= Var_Subst(NULL
, buf
, VAR_GLOBAL
, 0);
643 if (path
[0] != '/') {
644 snprintf(buf
, MAXPATHLEN
, "%s/%s", curdir
, path
);
648 /* look for the directory and try to chdir there */
649 if (stat(path
, &sb
) == 0 && S_ISDIR(sb
.st_mode
)) {
651 (void)fprintf(stderr
, "make warning: %s: %s.\n",
652 path
, strerror(errno
));
654 strncpy(objdir
, path
, MAXPATHLEN
);
655 Var_Set(".OBJDIR", objdir
, VAR_GLOBAL
, 0);
656 setenv("PWD", objdir
, 1);
668 * ReadAllMakefiles --
669 * wrapper around ReadMakefile() to read all.
672 * TRUE if ok, FALSE on error
675 ReadAllMakefiles(const void *p
, const void *q
)
677 return (ReadMakefile(p
, q
) == 0);
685 char dir
[MAXPATHLEN
];
686 char str
[2 * MAXPATHLEN
];
688 if (getcwd(dir
, sizeof(dir
)) == NULL
)
690 len
= snprintf(str
, sizeof(str
), "%s: Working in: %s\n", progname
, dir
);
692 (void)write(STDERR_FILENO
, str
, (size_t)len
);
698 * The main function, for obvious reasons. Initializes variables
699 * and a few modules, then parses the arguments give it in the
700 * environment and on the command line. Reads the system makefile
701 * followed by either Makefile, makefile or the file given by the
702 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
703 * flags it has received by then uses either the Make or the Compat
704 * module to create the initial list of targets.
707 * If -q was given, exits -1 if anything was out-of-date. Else it exits
711 * The program exits when done. Targets are created. etc. etc. etc.
714 main(int argc
, char **argv
)
716 Lst targs
; /* target nodes to create -- passed to Make_Init */
717 Boolean outOfDate
= FALSE
; /* FALSE if all targets up to date */
719 char *p1
, *path
, *pwd
;
720 char mdpath
[MAXPATHLEN
];
721 char *machine
= getenv("MACHINE");
722 const char *machine_arch
= getenv("MACHINE_ARCH");
723 char *syspath
= getenv("MAKESYSPATH");
724 Lst sysMkPath
; /* Path of sys.mk */
725 char *cp
= NULL
, *start
;
726 /* avoid faults on read-only strings */
727 static char defsyspath
[] = _PATH_DEFSYSPATH
;
728 char found_path
[MAXPATHLEN
+ 1]; /* for searching for sys.mk */
729 struct timeval rightnow
; /* to initialize random seed */
731 struct utsname utsname
;
734 /* default to writing debug to stderr */
738 (void)signal(SIGINFO
, siginfo
);
741 * Set the seed to produce a different random sequence
742 * on each program execution.
744 gettimeofday(&rightnow
, NULL
);
745 srandom(rightnow
.tv_sec
+ rightnow
.tv_usec
);
747 if ((progname
= strrchr(argv
[0], '/')) != NULL
)
751 #if defined(RLIMIT_NOFILE) && !defined(__minix)
753 * get rid of resource limit on file descriptors
757 if (getrlimit(RLIMIT_NOFILE
, &rl
) != -1 &&
758 rl
.rlim_cur
!= rl
.rlim_max
) {
759 rl
.rlim_cur
= rl
.rlim_max
;
760 (void)setrlimit(RLIMIT_NOFILE
, &rl
);
766 * Get the name of this type of MACHINE from utsname
767 * so we can share an executable for similar machines.
768 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
770 * Note that both MACHINE and MACHINE_ARCH are decided at
775 if (uname(&utsname
) == -1) {
776 (void)fprintf(stderr
, "%s: uname failed (%s).\n", progname
,
780 machine
= utsname
.machine
;
783 machine
= MAKE_MACHINE
;
792 #ifdef MAKE_MACHINE_ARCH
793 machine_arch
= MAKE_MACHINE_ARCH
;
795 machine_arch
= "unknown";
798 machine_arch
= MACHINE_ARCH
;
803 * Just in case MAKEOBJDIR wants us to do something tricky.
805 Var_Init(); /* Initialize the lists of variables for
806 * parsing arguments */
807 Var_Set("MACHINE", machine
, VAR_GLOBAL
, 0);
808 Var_Set("MACHINE_ARCH", machine_arch
, VAR_GLOBAL
, 0);
810 Var_Set("MAKE_VERSION", MAKE_VERSION
, VAR_GLOBAL
, 0);
812 Var_Set(".newline", "\n", VAR_GLOBAL
, 0); /* handy for :@ loops */
814 create
= Lst_Init(FALSE
);
815 makefiles
= Lst_Init(FALSE
);
817 variables
= Lst_Init(FALSE
);
818 beSilent
= FALSE
; /* Print commands as executed */
819 ignoreErrors
= FALSE
; /* Pay attention to non-zero returns */
820 noExecute
= FALSE
; /* Execute all commands */
821 noRecursiveExecute
= FALSE
; /* Execute all .MAKE targets */
822 keepgoing
= FALSE
; /* Stop on error */
823 allPrecious
= FALSE
; /* Remove targets when interrupted */
824 queryFlag
= FALSE
; /* This is not just a check-run */
825 noBuiltins
= FALSE
; /* Read the built-in rules */
826 touchFlag
= FALSE
; /* Actually update targets */
827 debug
= 0; /* No debug verbosity, please. */
830 maxJobs
= DEFMAXLOCAL
; /* Set default local max concurrency */
831 maxJobTokens
= maxJobs
;
832 compatMake
= FALSE
; /* No compat mode */
836 * Initialize the parsing, directory and variable modules to prepare
837 * for the reading of inclusion paths and variable settings on the
842 * Initialize various variables.
843 * MAKE also gets this name, for compatibility
844 * .MAKEFLAGS gets set to the empty string just in case.
845 * MFLAGS also gets initialized empty, for compatibility.
848 Var_Set("MAKE", argv
[0], VAR_GLOBAL
, 0);
849 Var_Set(".MAKE", argv
[0], VAR_GLOBAL
, 0);
850 Var_Set(MAKEFLAGS
, "", VAR_GLOBAL
, 0);
851 Var_Set(MAKEOVERRIDES
, "", VAR_GLOBAL
, 0);
852 Var_Set("MFLAGS", "", VAR_GLOBAL
, 0);
853 Var_Set(".ALLTARGETS", "", VAR_GLOBAL
, 0);
856 * Set some other useful macros
862 if (!(ep
= getenv(MAKE_LEVEL
))) {
865 Var_Set(MAKE_LEVEL
, ep
, VAR_GLOBAL
, 0);
866 snprintf(tmp
, sizeof(tmp
), "%u", getpid());
867 Var_Set(".MAKE.PID", tmp
, VAR_GLOBAL
, 0);
868 snprintf(tmp
, sizeof(tmp
), "%u", getppid());
869 Var_Set(".MAKE.PPID", tmp
, VAR_GLOBAL
, 0);
874 * First snag any flags out of the MAKE environment variable.
875 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
876 * in a different format).
879 Main_ParseArgLine(getenv("MAKEFLAGS"));
881 Main_ParseArgLine(getenv("MAKE"));
884 MainParseArgs(argc
, argv
);
887 * Find where we are (now) and take care of PWD for the automounter...
888 * All this code is so that we know where we are when we start up
889 * on a different machine with pmake.
891 if (getcwd(curdir
, MAXPATHLEN
) == NULL
) {
892 (void)fprintf(stderr
, "%s: %s.\n", progname
, strerror(errno
));
896 if (stat(curdir
, &sa
) == -1) {
897 (void)fprintf(stderr
, "%s: %s: %s.\n",
898 progname
, curdir
, strerror(errno
));
903 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
904 * since the value of curdir can vary depending on how we got
905 * here. Ie sitting at a shell prompt (shell that provides $PWD)
906 * or via subdir.mk in which case its likely a shell which does
908 * So, to stop it breaking this case only, we ignore PWD if
909 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
912 (pwd
= getenv("PWD")) != NULL
&&
913 getenv("MAKEOBJDIRPREFIX") == NULL
) {
914 const char *makeobjdir
= getenv("MAKEOBJDIR");
916 if (makeobjdir
== NULL
|| !strchr(makeobjdir
, '$')) {
917 if (stat(pwd
, &sb
) == 0 && sa
.st_ino
== sb
.st_ino
&&
918 sa
.st_dev
== sb
.st_dev
)
919 (void)strncpy(curdir
, pwd
, MAXPATHLEN
);
922 Var_Set(".CURDIR", curdir
, VAR_GLOBAL
, 0);
925 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
926 * MAKEOBJDIR is set in the environment, try only that value
927 * and fall back to .CURDIR if it does not exist.
929 * Otherwise, try _PATH_OBJDIR.MACHINE, _PATH_OBJDIR, and
930 * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
931 * of these paths exist, just use .CURDIR.
934 (void)Main_SetObjdir(curdir
);
936 if ((path
= getenv("MAKEOBJDIRPREFIX")) != NULL
) {
937 (void)snprintf(mdpath
, MAXPATHLEN
, "%s%s", path
, curdir
);
938 (void)Main_SetObjdir(mdpath
);
939 } else if ((path
= getenv("MAKEOBJDIR")) != NULL
) {
940 (void)Main_SetObjdir(path
);
942 (void)snprintf(mdpath
, MAXPATHLEN
, "%s.%s", _PATH_OBJDIR
, machine
);
943 if (!Main_SetObjdir(mdpath
) && !Main_SetObjdir(_PATH_OBJDIR
)) {
944 (void)snprintf(mdpath
, MAXPATHLEN
, "%s%s",
945 _PATH_OBJDIRPREFIX
, curdir
);
946 (void)Main_SetObjdir(mdpath
);
951 * Be compatible if user did not specify -j and did not explicitly
952 * turned compatibility on
954 if (!compatMake
&& !forceJobs
) {
959 * Initialize archive, target and suffix modules in preparation for
960 * parsing the makefile(s)
965 Trace_Init(tracefile
);
970 Trace_Log(MAKESTART
, NULL
);
973 * Set up the .TARGETS variable to contain the list of targets to be
974 * created. If none specified, make the variable empty -- the parser
975 * will fill the thing in with the default or .MAIN target.
977 if (!Lst_IsEmpty(create
)) {
980 for (ln
= Lst_First(create
); ln
!= NULL
;
982 char *name
= (char *)Lst_Datum(ln
);
984 Var_Append(".TARGETS", name
, VAR_GLOBAL
);
987 Var_Set(".TARGETS", "", VAR_GLOBAL
, 0);
991 * If no user-supplied system path was given (through the -m option)
992 * add the directories from the DEFSYSPATH (more than one may be given
993 * as dir1:...:dirn) to the system include path.
995 if (syspath
== NULL
|| *syspath
== '\0')
996 syspath
= defsyspath
;
998 syspath
= bmake_strdup(syspath
);
1000 for (start
= syspath
; *start
!= '\0'; start
= cp
) {
1001 for (cp
= start
; *cp
!= '\0' && *cp
!= ':'; cp
++)
1006 /* look for magic parent directory search string */
1007 if (strncmp(".../", start
, 4) != 0) {
1008 (void)Dir_AddDir(defIncPath
, start
);
1010 if (Dir_FindHereOrAbove(curdir
, start
+4,
1011 found_path
, sizeof(found_path
))) {
1012 (void)Dir_AddDir(defIncPath
, found_path
);
1016 if (syspath
!= defsyspath
)
1020 * Read in the built-in rules first, followed by the specified
1021 * makefile, if it was (makefile != NULL), or the default
1022 * makefile and Makefile, in that order, if it wasn't.
1027 sysMkPath
= Lst_Init(FALSE
);
1028 Dir_Expand(_PATH_DEFSYSMK
,
1029 Lst_IsEmpty(sysIncPath
) ? defIncPath
: sysIncPath
,
1031 if (Lst_IsEmpty(sysMkPath
))
1032 Fatal("%s: no system rules (%s).", progname
,
1034 ln
= Lst_Find(sysMkPath
, NULL
, ReadMakefile
);
1036 Fatal("%s: cannot open %s.", progname
,
1037 (char *)Lst_Datum(ln
));
1040 if (!Lst_IsEmpty(makefiles
)) {
1043 ln
= Lst_Find(makefiles
, NULL
, ReadAllMakefiles
);
1045 Fatal("%s: cannot open %s.", progname
,
1046 (char *)Lst_Datum(ln
));
1047 } else if (ReadMakefile("makefile", NULL
) != 0)
1048 (void)ReadMakefile("Makefile", NULL
);
1050 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1051 if (!noBuiltins
|| !printVars
) {
1052 doing_depend
= TRUE
;
1053 (void)ReadMakefile(".depend", NULL
);
1054 doing_depend
= FALSE
;
1057 Var_Append("MFLAGS", Var_Value(MAKEFLAGS
, VAR_GLOBAL
, &p1
), VAR_GLOBAL
);
1062 Job_ServerStart(maxJobTokens
, jp_0
, jp_1
);
1064 fprintf(debug_file
, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1065 jp_0
, jp_1
, maxJobs
, maxJobTokens
, compatMake
);
1067 Main_ExportMAKEFLAGS(TRUE
); /* initial export */
1069 Check_Cwd_av(0, NULL
, 0); /* initialize it */
1073 * For compatibility, look at the directories in the VPATH variable
1074 * and add them to the search path, if the variable is defined. The
1075 * variable's value is in the same format as the PATH envariable, i.e.
1076 * <directory>:<directory>:<directory>...
1078 if (Var_Exists("VPATH", VAR_CMD
)) {
1081 * GCC stores string constants in read-only memory, but
1082 * Var_Subst will want to write this thing, so store it
1085 static char VPATH
[] = "${VPATH}";
1087 vpath
= Var_Subst(NULL
, VPATH
, VAR_CMD
, FALSE
);
1090 /* skip to end of directory */
1091 for (cp
= path
; *cp
!= ':' && *cp
!= '\0'; cp
++)
1093 /* Save terminator character so know when to stop */
1096 /* Add directory to search path */
1097 (void)Dir_AddDir(dirSearchPath
, path
);
1100 } while (savec
== ':');
1105 * Now that all search paths have been read for suffixes et al, it's
1106 * time to add the default search path to their lists...
1111 * Propagate attributes through :: dependency lists.
1115 /* print the initial graph, if the user requested it */
1119 /* print the values of any variables requested by the user */
1123 for (ln
= Lst_First(variables
); ln
!= NULL
;
1124 ln
= Lst_Succ(ln
)) {
1125 char *var
= (char *)Lst_Datum(ln
);
1128 if (strchr(var
, '$')) {
1129 value
= p1
= Var_Subst(NULL
, var
, VAR_GLOBAL
, 0);
1131 value
= Var_Value(var
, VAR_GLOBAL
, &p1
);
1133 printf("%s\n", value
? value
: "");
1139 * Have now read the entire graph and need to make a list of
1140 * targets to create. If none was given on the command line,
1141 * we consult the parsing module to find the main target(s)
1144 if (Lst_IsEmpty(create
))
1145 targs
= Parse_MainName();
1147 targs
= Targ_FindList(create
, TARG_CREATE
);
1151 * Initialize job module before traversing the graph
1152 * now that any .BEGIN and .END targets have been read.
1153 * This is done only if the -q flag wasn't given
1154 * (to prevent the .BEGIN from being executed should
1162 /* Traverse the graph, checking on all the targets */
1163 outOfDate
= Make_Run(targs
);
1166 * Compat_Init will take care of creating all the
1167 * targets as well as initializing the module.
1174 Lst_Destroy(targs
, NULL
);
1175 Lst_Destroy(variables
, NULL
);
1176 Lst_Destroy(makefiles
, NULL
);
1177 Lst_Destroy(create
, (FreeProc
*)free
);
1180 /* print the graph now it's been processed if the user requested it */
1184 Trace_Log(MAKEEND
, 0);
1195 return outOfDate
? 1 : 0;
1200 * Open and parse the given makefile.
1203 * 0 if ok. -1 if couldn't open file.
1209 ReadMakefile(const void *p
, const void *q __unused
)
1211 const char *fname
= p
; /* makefile to read */
1213 size_t len
= MAXPATHLEN
;
1214 char *name
, *path
= bmake_malloc(len
);
1217 if (!strcmp(fname
, "-")) {
1218 Parse_File("(stdin)", dup(fileno(stdin
)));
1219 Var_Set("MAKEFILE", "", VAR_GLOBAL
, 0);
1221 setMAKEFILE
= strcmp(fname
, ".depend");
1223 /* if we've chdir'd, rebuild the path name */
1224 if (strcmp(curdir
, objdir
) && *fname
!= '/') {
1225 size_t plen
= strlen(curdir
) + strlen(fname
) + 2;
1227 path
= bmake_realloc(path
, len
= 2 * plen
);
1229 (void)snprintf(path
, len
, "%s/%s", curdir
, fname
);
1230 fd
= open(path
, O_RDONLY
);
1236 /* If curdir failed, try objdir (ala .depend) */
1237 plen
= strlen(objdir
) + strlen(fname
) + 2;
1239 path
= bmake_realloc(path
, len
= 2 * plen
);
1240 (void)snprintf(path
, len
, "%s/%s", objdir
, fname
);
1241 fd
= open(path
, O_RDONLY
);
1247 fd
= open(fname
, O_RDONLY
);
1251 /* look in -I and system include directories. */
1252 name
= Dir_FindFile(fname
, parseIncPath
);
1254 name
= Dir_FindFile(fname
,
1255 Lst_IsEmpty(sysIncPath
) ? defIncPath
: sysIncPath
);
1256 if (!name
|| (fd
= open(name
, O_RDONLY
)) == -1) {
1264 * set the MAKEFILE variable desired by System V fans -- the
1265 * placement of the setting here means it gets set to the last
1266 * makefile specified, as it is set by SysV make.
1270 Var_Set("MAKEFILE", fname
, VAR_GLOBAL
, 0);
1271 Parse_File(fname
, fd
);
1279 * If MAKEOBJDIRPREFIX is in use, make ends up not in .CURDIR
1280 * in situations that would not arrise with ./obj (links or not).
1281 * This tends to break things like:
1286 * This function spots when ${.MAKE:T} or ${.MAKE} is a command (as
1287 * opposed to an argument) in a command line and if so returns
1288 * ${.CURDIR} so caller can chdir() so that the assumptions made by
1289 * the Makefile hold true.
1291 * If ${.MAKE} does not contain any '/', then ${.MAKE:T} is skipped.
1293 * The chdir() only happens in the child process, and does nothing if
1294 * MAKEOBJDIRPREFIX and MAKEOBJDIR are not in the environment so it
1295 * should not break anything. Also if NOCHECKMAKECHDIR is set we
1296 * do nothing - to ensure historic semantics can be retained.
1298 static int Check_Cwd_Off
= 0;
1301 Check_Cwd_av(int ac
, char **av
, int copy
)
1303 static char *make
[4];
1304 static char *cur_dir
= NULL
;
1307 int is_cmd
, next_cmd
;
1311 if (Check_Cwd_Off
) {
1313 fprintf(debug_file
, "check_cwd: check is off.\n");
1317 if (make
[0] == NULL
) {
1318 if (Var_Exists("NOCHECKMAKECHDIR", VAR_GLOBAL
)) {
1321 fprintf(debug_file
, "check_cwd: turning check off.\n");
1325 make
[1] = Var_Value(".MAKE", VAR_GLOBAL
, &cp
);
1326 if ((make
[0] = strrchr(make
[1], '/')) == NULL
) {
1332 cur_dir
= Var_Value(".CURDIR", VAR_GLOBAL
, &cp
);
1334 if (ac
== 0 || av
== NULL
) {
1336 fprintf(debug_file
, "check_cwd: empty command.\n");
1337 return NULL
; /* initialization only */
1340 if (getenv("MAKEOBJDIR") == NULL
&&
1341 getenv("MAKEOBJDIRPREFIX") == NULL
) {
1343 fprintf(debug_file
, "check_cwd: no obj dirs.\n");
1349 for (i
= 0; i
< ac
; ++i
) {
1353 cp
= &(av
[i
])[n
- 1];
1354 if (strspn(av
[i
], "|&;") == (size_t)n
) {
1357 } else if (*cp
== ';' || *cp
== '&' || *cp
== '|' || *cp
== ')') {
1362 } while (*cp
== ';' || *cp
== '&' || *cp
== '|' ||
1363 *cp
== ')' || *cp
== '}') ;
1366 * XXX this should not happen.
1368 fprintf(stderr
, "%s: WARNING: raw arg ends in shell meta '%s'\n",
1375 if (*cp
== ';' || *cp
== '&' || *cp
== '|')
1379 fprintf(debug_file
, "av[%d] == %s '%s'",
1380 i
, (is_cmd
) ? "cmd" : "arg", av
[i
]);
1382 if (*cp
== '(' || *cp
== '{' ||
1383 *cp
== ';' || *cp
== '&' || *cp
== '|') {
1386 } while (*cp
== '(' || *cp
== '{' ||
1387 *cp
== ';' || *cp
== '&' || *cp
== '|');
1393 if (strcmp(cp
, "cd") == 0 || strcmp(cp
, "chdir") == 0) {
1395 fprintf(debug_file
, " == cd, done.\n");
1398 for (mp
= make
; *mp
!= NULL
; ++mp
) {
1400 if (strcmp(cp
, *mp
) == 0) {
1402 fprintf(debug_file
, " %s == '%s', chdir(%s)\n",
1409 fprintf(debug_file
, "\n");
1415 Check_Cwd_Cmd(const char *cmd
)
1425 av
= brk_string(cmd
, &ac
, TRUE
, &bp
);
1427 fprintf(debug_file
, "splitting: '%s' -> %d words\n",
1434 cp
= Check_Cwd_av(ac
, av
, 1);
1443 Check_Cwd(const char **argv
)
1451 for (ac
= 0; argv
[ac
] != NULL
; ++ac
)
1453 if (ac
== 3 && *argv
[1] == '-') {
1454 cp
= Check_Cwd_Cmd(argv
[2]);
1456 cp
= Check_Cwd_av(ac
, UNCONST(argv
), 0);
1465 * Execute the command in cmd, and return the output of that command
1469 * A string containing the output of the command, or the empty string
1470 * If errnum is not NULL, it contains the reason for the command failure
1473 * The string must be freed by the caller.
1476 Cmd_Exec(const char *cmd
, const char **errnum
)
1478 const char *args
[4]; /* Args for invoking the shell */
1479 int fds
[2]; /* Pipe streams */
1480 int cpid
; /* Child PID */
1481 int pid
; /* PID from wait() */
1482 char *res
; /* result */
1483 int status
; /* command exit status */
1484 Buffer buf
; /* buffer to store the result */
1494 * Set up arguments for shell
1496 args
[0] = shellName
;
1502 * Open a pipe for fetching its output
1504 if (pipe(fds
) == -1) {
1505 *errnum
= "Couldn't create pipe for \"%s\"";
1512 #if defined(__minix)
1513 switch (cpid
= fork()) {
1515 switch (cpid
= vfork()) {
1519 * Close input side of pipe
1521 (void)close(fds
[0]);
1524 * Duplicate the output stream to the shell's output, then
1525 * shut the extra thing down. Note we don't fetch the error
1526 * stream...why not? Why?
1528 (void)dup2(fds
[1], 1);
1529 (void)close(fds
[1]);
1533 (void)execv(shellPath
, UNCONST(args
));
1538 *errnum
= "Couldn't exec \"%s\"";
1543 * No need for the writing half
1545 (void)close(fds
[1]);
1550 char result
[BUFSIZ
];
1551 cc
= read(fds
[0], result
, sizeof(result
));
1553 Buf_AddBytes(&buf
, cc
, result
);
1555 while (cc
> 0 || (cc
== -1 && errno
== EINTR
));
1558 * Close the input side of the pipe.
1560 (void)close(fds
[0]);
1563 * Wait for the process to exit.
1565 while(((pid
= waitpid(cpid
, &status
, 0)) != cpid
) && (pid
>= 0))
1568 cc
= Buf_Size(&buf
);
1569 res
= Buf_Destroy(&buf
, FALSE
);
1572 *errnum
= "Couldn't read shell's output for \"%s\"";
1574 if (WIFSIGNALED(status
))
1575 *errnum
= "\"%s\" exited on a signal";
1576 else if (WEXITSTATUS(status
) != 0)
1577 *errnum
= "\"%s\" returned non-zero status";
1580 * Null-terminate the result, convert newlines to spaces and
1581 * install it in the variable.
1586 if (cc
> 0 && *--cp
== '\n') {
1588 * A final newline is just stripped
1602 res
= bmake_malloc(1);
1609 * Print an error message given its format.
1615 * The message is printed.
1619 Error(const char *fmt
, ...)
1624 err_file
= debug_file
;
1625 if (err_file
== stdout
)
1629 fprintf(err_file
, "%s: ", progname
);
1630 (void)vfprintf(err_file
, fmt
, ap
);
1632 (void)fprintf(err_file
, "\n");
1633 (void)fflush(err_file
);
1634 if (err_file
== stderr
)
1642 * Produce a Fatal error message. If jobs are running, waits for them
1653 Fatal(const char *fmt
, ...)
1661 (void)vfprintf(stderr
, fmt
, ap
);
1663 (void)fprintf(stderr
, "\n");
1664 (void)fflush(stderr
);
1668 if (DEBUG(GRAPH2
) || DEBUG(GRAPH3
))
1670 Trace_Log(MAKEERROR
, 0);
1671 exit(2); /* Not 1 so -q can distinguish error */
1676 * Major exception once jobs are being created. Kills all jobs, prints
1677 * a message and exits.
1683 * All children are killed indiscriminately and the program Lib_Exits
1687 Punt(const char *fmt
, ...)
1692 (void)fprintf(stderr
, "%s: ", progname
);
1693 (void)vfprintf(stderr
, fmt
, ap
);
1695 (void)fprintf(stderr
, "\n");
1696 (void)fflush(stderr
);
1705 * Exit without giving a message.
1720 Trace_Log(MAKEERROR
, 0);
1721 exit(2); /* Not 1, so -q can distinguish error */
1726 * Called when aborting due to errors in child shell to signal
1737 /* number of errors encountered in Make_Make */
1739 Fatal("%d error%s", errors
, errors
== 1 ? "" : "s");
1744 * Remove a file carefully, avoiding directories.
1747 eunlink(const char *file
)
1751 if (lstat(file
, &st
) == -1)
1754 if (S_ISDIR(st
.st_mode
)) {
1758 return unlink(file
);
1763 * Print why exec failed, avoiding stdio.
1766 execError(const char *af
, const char *av
)
1770 struct iovec iov
[8];
1772 (void)(iov[i].iov_base = UNCONST(s), \
1773 iov[i].iov_len = strlen(iov[i].iov_base), \
1776 #define IOADD(void)write(2, s, strlen(s))
1784 IOADD(") failed (");
1785 IOADD(strerror(errno
));
1789 (void)writev(2, iov
, 8);
1795 * exit with usage message
1800 (void)fprintf(stderr
,
1801 "usage: %s [-BeikNnqrstWX] \n\
1802 [-C directory] [-D variable] [-d flags] [-f makefile]\n\
1803 [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1804 [-V variable] [variable=value] [target ...]\n", progname
);
1810 PrintAddr(void *a
, void *b
)
1812 printf("%lx ", (unsigned long) a
);
1819 PrintOnError(const char *s
)
1827 printf("\n%s: stopped in %s\n", progname
, curdir
);
1828 strncpy(tmp
, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1830 cp
= Var_Subst(NULL
, tmp
, VAR_GLOBAL
, 0);
1839 Main_ExportMAKEFLAGS(Boolean first
)
1841 static int once
= 1;
1849 strncpy(tmp
, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1851 s
= Var_Subst(NULL
, tmp
, VAR_CMD
, 0);
1854 setenv("MAKEFLAGS", s
, 1);
1856 setenv("MAKE", s
, 1);