1
/* $NetBSD: main.c,v 1.224 2013/09/04 15:38:26 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.224 2013/09/04 15:38:26 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.224 2013/09/04 15:38:26 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/stat.h>
121
#include <sys/utsname.h>
137
#include "pathnames.h"
145
#define DEFMAXLOCAL DEFMAXJOBS
146
#endif /* DEFMAXLOCAL */
148
Lst create; /* Targets to be made */
149
time_t now; /* Time at start of make */
150
GNode *DEFAULT; /* .DEFAULT node */
151
Boolean allPrecious; /* .PRECIOUS given on line by itself */
153
static Boolean noBuiltins; /* -r flag */
154
static Lst makefiles; /* ordered list of makefiles to read */
155
static Boolean printVars; /* print value of one or more vars */
156
static Lst variables; /* list of variables to print */
157
int maxJobs; /* -j argument */
158
static int maxJobTokens; /* -j argument */
159
Boolean compatMake; /* -B argument */
160
int debug; /* -d argument */
161
Boolean debugVflag; /* -dV */
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 enterFlag; /* -w flag */
168
Boolean ignoreErrors; /* -i flag */
169
Boolean beSilent; /* -s flag */
170
Boolean oldVars; /* variable substitution style */
171
Boolean checkEnvFirst; /* -e flag */
172
Boolean parseWarnFatal; /* -W flag */
173
Boolean jobServer; /* -J flag */
174
static int jp_0 = -1, jp_1 = -1; /* ends of parent job pipe */
175
Boolean varNoExportEnv; /* -X flag */
176
Boolean doing_depend; /* Set while reading .depend */
177
static Boolean jobsRunning; /* TRUE if the jobs might be running */
178
static const char * tracefile;
179
static void MainParseArgs(int, char **);
180
static int ReadMakefile(const void *, const void *);
181
static void usage(void) MAKE_ATTR_DEAD;
183
static Boolean ignorePWD; /* if we use -C, PWD is meaningless */
184
static char objdir[MAXPATHLEN + 1]; /* where we chdir'ed to */
185
char curdir[MAXPATHLEN + 1]; /* Startup directory */
186
char *progname; /* the program name */
187
char *makeDependfile;
191
Boolean forceJobs = FALSE;
194
* On some systems MACHINE is defined as something other than
199
# define MACHINE FORCE_MACHINE
202
extern Lst parseIncPath;
205
* For compatibility with the POSIX version of MAKEFLAGS that includes
206
* all the options with out -, convert flags to -f -l -a -g -s.
209
explode(const char *flags)
218
for (f = flags; *f; f++)
219
if (!isalpha((unsigned char)*f))
223
return bmake_strdup(flags);
226
st = nf = bmake_malloc(len * 3 + 1);
237
parse_debug_options(const char *argvalue)
244
for (modules = argvalue; *modules; ++modules) {
262
debug |= DEBUG_ERROR;
268
if (modules[1] == '1') {
269
debug |= DEBUG_GRAPH1;
272
else if (modules[1] == '2') {
273
debug |= DEBUG_GRAPH2;
276
else if (modules[1] == '3') {
277
debug |= DEBUG_GRAPH3;
294
debug |= DEBUG_SCRIPT;
297
debug |= DEBUG_PARSE;
312
debug |= DEBUG_SHELL;
315
if (debug_file != stdout && debug_file != stderr)
317
if (*++modules == '+') {
322
if (strcmp(modules, "stdout") == 0) {
326
if (strcmp(modules, "stderr") == 0) {
330
len = strlen(modules);
331
fname = malloc(len + 20);
332
memcpy(fname, modules, len + 1);
333
/* Let the filename be modified by the pid */
334
if (strcmp(fname + len - 3, ".%d") == 0)
335
snprintf(fname + len - 2, 20, "%d", getpid());
336
debug_file = fopen(fname, mode);
338
fprintf(stderr, "Cannot open debug file %s\n",
345
(void)fprintf(stderr,
346
"%s: illegal argument to d option -- %c\n",
353
* Make the debug_file unbuffered, and make
354
* stdout line buffered (unless debugfile == stdout).
356
setvbuf(debug_file, NULL, _IONBF, 0);
357
if (debug_file != stdout) {
358
setvbuf(stdout, NULL, _IOLBF, 0);
364
* Parse a given argument vector. Called from main() and from
365
* Main_ParseArgLine() when the .MAKEFLAGS target is used.
367
* XXX: Deal with command line overriding .MAKEFLAGS in makefile
373
* Various global and local flags will be set depending on the flags
377
MainParseArgs(int argc, char **argv)
383
const char *getopt_def;
385
Boolean inOption, dashDash = FALSE;
386
char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
388
#define OPTFLAGS "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrstw"
389
/* Can't actually use getopt(3) because rescanning is not portable */
391
getopt_def = OPTFLAGS;
409
if (c != '-' || dashDash)
414
/* '-' found at some earlier point */
415
getopt_spec = strchr(getopt_def, c);
416
if(c != '\0' && getopt_spec != NULL && getopt_spec[1] == ':') {
417
/* -<something> found, and <something> should have an arg */
421
if(*argvalue == '\0') {
437
Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
438
Var_Set(MAKE_MODE, "compat", VAR_GLOBAL, 0);
441
if (chdir(argvalue) == -1) {
442
(void)fprintf(stderr,
443
"%s: chdir %s: %s\n",
448
if (getcwd(curdir, MAXPATHLEN) == NULL) {
449
(void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
455
if (argvalue == NULL || argvalue[0] == 0) goto noarg;
456
Var_Set(argvalue, "1", VAR_GLOBAL, 0);
457
Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
458
Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
461
if (argvalue == NULL) goto noarg;
462
Parse_AddIncludeDir(argvalue);
463
Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
464
Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
467
if (argvalue == NULL) goto noarg;
468
if (sscanf(argvalue, "%d,%d", &jp_0, &jp_1) != 2) {
469
(void)fprintf(stderr,
470
"%s: internal error -- J option malformed (%s)\n",
474
if ((fcntl(jp_0, F_GETFD, 0) < 0) ||
475
(fcntl(jp_1, F_GETFD, 0) < 0)) {
477
(void)fprintf(stderr,
478
"%s: ###### warning -- J descriptors were closed!\n",
486
Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
487
Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
493
noRecursiveExecute = TRUE;
494
Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
498
Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
501
if (argvalue == NULL) goto noarg;
502
tracefile = bmake_strdup(argvalue);
503
Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
504
Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
507
if (argvalue == NULL) goto noarg;
509
(void)Lst_AtEnd(variables, argvalue);
510
Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
511
Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
514
parseWarnFatal = TRUE;
517
varNoExportEnv = TRUE;
518
Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
521
if (argvalue == NULL) goto noarg;
522
/* If '-d-opts' don't pass to children */
523
if (argvalue[0] == '-')
526
Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
527
Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
529
parse_debug_options(argvalue);
532
checkEnvFirst = TRUE;
533
Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
536
if (argvalue == NULL) goto noarg;
537
(void)Lst_AtEnd(makefiles, argvalue);
541
Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
544
if (argvalue == NULL) goto noarg;
546
maxJobs = strtol(argvalue, &p, 0);
547
if (*p != '\0' || maxJobs < 1) {
548
(void)fprintf(stderr, "%s: illegal argument to -j -- must be positive integer!\n",
552
Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
553
Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
554
Var_Set(".MAKE.JOBS", argvalue, VAR_GLOBAL, 0);
555
maxJobTokens = maxJobs;
559
Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
562
if (argvalue == NULL) goto noarg;
563
/* look for magic parent directory search string */
564
if (strncmp(".../", argvalue, 4) == 0) {
565
if (!Dir_FindHereOrAbove(curdir, argvalue+4,
566
found_path, sizeof(found_path)))
567
break; /* nothing doing */
568
(void)Dir_AddDir(sysIncPath, found_path);
570
(void)Dir_AddDir(sysIncPath, argvalue);
572
Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
573
Var_Append(MAKEFLAGS, argvalue, VAR_GLOBAL);
577
Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
581
/* Kind of nonsensical, wot? */
582
Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
586
Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
590
Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
594
Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
598
Var_Append(MAKEFLAGS, "-w", VAR_GLOBAL);
606
fprintf(stderr, "getopt(%s) -> %d (%c)\n",
618
* See if the rest of the arguments are variable assignments and
619
* perform them if so. Else take them to be targets and stuff them
620
* on the end of the "create" list.
622
for (; argc > 1; ++argv, --argc)
623
if (Parse_IsVar(argv[1])) {
624
Parse_DoVar(argv[1], VAR_CMD);
627
Punt("illegal (null) argument.");
628
if (*argv[1] == '-' && !dashDash)
630
(void)Lst_AtEnd(create, bmake_strdup(argv[1]));
635
(void)fprintf(stderr, "%s: option requires an argument -- %c\n",
641
* Main_ParseArgLine --
642
* Used by the parse module when a .MFLAGS or .MAKEFLAGS target
643
* is encountered and by main() when reading the .MAKEFLAGS envariable.
644
* Takes a line of arguments and breaks it into its
645
* component words and passes those words and the number of them to the
646
* MainParseArgs function.
647
* The line should have all its leading whitespace removed.
650
* line Line to fracture
656
* Only those that come from the various arguments.
659
Main_ParseArgLine(const char *line)
661
char **argv; /* Manufactured argument vector */
662
int argc; /* Number of arguments in argv */
663
char *args; /* Space used by the args */
665
char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
670
for (; *line == ' '; ++line)
678
* $MAKE may simply be naming the make(1) binary
682
if (!(cp = strrchr(line, '/')))
684
if ((cp = strstr(cp, "make")) &&
685
strcmp(cp, "make") == 0)
689
buf = bmake_malloc(len = strlen(line) + strlen(argv0) + 2);
690
(void)snprintf(buf, len, "%s %s", argv0, line);
694
argv = brk_string(buf, &argc, TRUE, &args);
696
Error("Unterminated quoted string [%s]", buf);
701
MainParseArgs(argc, argv);
708
Main_SetObjdir(const char *path)
712
char buf[MAXPATHLEN + 1];
715
/* expand variable substitutions */
716
if (strchr(path, '$') != 0) {
717
snprintf(buf, MAXPATHLEN, "%s", path);
718
path = p = Var_Subst(NULL, buf, VAR_GLOBAL, 0);
721
if (path[0] != '/') {
722
snprintf(buf, MAXPATHLEN, "%s/%s", curdir, path);
726
/* look for the directory and try to chdir there */
727
if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
729
(void)fprintf(stderr, "make warning: %s: %s.\n",
730
path, strerror(errno));
732
strncpy(objdir, path, MAXPATHLEN);
733
Var_Set(".OBJDIR", objdir, VAR_GLOBAL, 0);
734
setenv("PWD", objdir, 1);
746
* ReadAllMakefiles --
747
* wrapper around ReadMakefile() to read all.
750
* TRUE if ok, FALSE on error
753
ReadAllMakefiles(const void *p, const void *q)
755
return (ReadMakefile(p, q) == 0);
759
str2Lst_Append(Lst lp, char *str, const char *sep)
767
for (n = 0, cp = strtok(str, sep); cp; cp = strtok(NULL, sep)) {
768
(void)Lst_AtEnd(lp, cp);
777
siginfo(int signo MAKE_ATTR_UNUSED)
779
char dir[MAXPATHLEN];
780
char str[2 * MAXPATHLEN];
782
if (getcwd(dir, sizeof(dir)) == NULL)
784
len = snprintf(str, sizeof(str), "%s: Working in: %s\n", progname, dir);
786
(void)write(STDERR_FILENO, str, (size_t)len);
791
* Allow makefiles some control over the mode we run in.
794
MakeMode(const char *mode)
799
mode = mp = Var_Subst(NULL, "${" MAKE_MODE ":tl}", VAR_GLOBAL, 0);
802
if (strstr(mode, "compat")) {
807
if (strstr(mode, "meta"))
808
meta_mode_init(mode);
817
* The main function, for obvious reasons. Initializes variables
818
* and a few modules, then parses the arguments give it in the
819
* environment and on the command line. Reads the system makefile
820
* followed by either Makefile, makefile or the file given by the
821
* -f argument. Sets the .MAKEFLAGS PMake variable based on all the
822
* flags it has received by then uses either the Make or the Compat
823
* module to create the initial list of targets.
826
* If -q was given, exits -1 if anything was out-of-date. Else it exits
830
* The program exits when done. Targets are created. etc. etc. etc.
833
main(int argc, char **argv)
835
Lst targs; /* target nodes to create -- passed to Make_Init */
836
Boolean outOfDate = FALSE; /* FALSE if all targets up to date */
839
char mdpath[MAXPATHLEN];
841
const char *machine = FORCE_MACHINE;
843
const char *machine = getenv("MACHINE");
845
const char *machine_arch = getenv("MACHINE_ARCH");
846
char *syspath = getenv("MAKESYSPATH");
847
Lst sysMkPath; /* Path of sys.mk */
848
char *cp = NULL, *start;
849
/* avoid faults on read-only strings */
850
static char defsyspath[] = _PATH_DEFSYSPATH;
851
char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
852
struct timeval rightnow; /* to initialize random seed */
853
struct utsname utsname;
855
/* default to writing debug to stderr */
859
(void)bmake_signal(SIGINFO, siginfo);
862
* Set the seed to produce a different random sequence
863
* on each program execution.
865
gettimeofday(&rightnow, NULL);
866
srandom(rightnow.tv_sec + rightnow.tv_usec);
868
if ((progname = strrchr(argv[0], '/')) != NULL)
872
#if defined(MAKE_NATIVE) || (defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE))
874
* get rid of resource limit on file descriptors
878
if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
879
rl.rlim_cur != rl.rlim_max) {
880
rl.rlim_cur = rl.rlim_max;
881
(void)setrlimit(RLIMIT_NOFILE, &rl);
886
if (uname(&utsname) == -1) {
887
(void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
893
* Get the name of this type of MACHINE from utsname
894
* so we can share an executable for similar machines.
895
* (i.e. m68k: amiga hp300, mac68k, sun3, ...)
897
* Note that both MACHINE and MACHINE_ARCH are decided at
902
machine = utsname.machine;
905
machine = MAKE_MACHINE;
914
#ifdef MAKE_MACHINE_ARCH
915
machine_arch = MAKE_MACHINE_ARCH;
917
machine_arch = "unknown";
920
machine_arch = MACHINE_ARCH;
924
myPid = getpid(); /* remember this for vFork() */
927
* Just in case MAKEOBJDIR wants us to do something tricky.
929
Var_Init(); /* Initialize the lists of variables for
930
* parsing arguments */
931
Var_Set(".MAKE.OS", utsname.sysname, VAR_GLOBAL, 0);
932
Var_Set("MACHINE", machine, VAR_GLOBAL, 0);
933
Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL, 0);
935
Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL, 0);
937
Var_Set(".newline", "\n", VAR_GLOBAL, 0); /* handy for :@ loops */
939
* This is the traditional preference for makefiles.
941
#ifndef MAKEFILE_PREFERENCE_LIST
942
# define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
944
Var_Set(MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST,
946
Var_Set(MAKE_DEPENDFILE, ".depend", VAR_GLOBAL, 0);
948
create = Lst_Init(FALSE);
949
makefiles = Lst_Init(FALSE);
952
variables = Lst_Init(FALSE);
953
beSilent = FALSE; /* Print commands as executed */
954
ignoreErrors = FALSE; /* Pay attention to non-zero returns */
955
noExecute = FALSE; /* Execute all commands */
956
noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
957
keepgoing = FALSE; /* Stop on error */
958
allPrecious = FALSE; /* Remove targets when interrupted */
959
queryFlag = FALSE; /* This is not just a check-run */
960
noBuiltins = FALSE; /* Read the built-in rules */
961
touchFlag = FALSE; /* Actually update targets */
962
debug = 0; /* No debug verbosity, please. */
965
maxJobs = DEFMAXLOCAL; /* Set default local max concurrency */
966
maxJobTokens = maxJobs;
967
compatMake = FALSE; /* No compat mode */
971
* Initialize the parsing, directory and variable modules to prepare
972
* for the reading of inclusion paths and variable settings on the
977
* Initialize various variables.
978
* MAKE also gets this name, for compatibility
979
* .MAKEFLAGS gets set to the empty string just in case.
980
* MFLAGS also gets initialized empty, for compatibility.
983
if (argv[0][0] == '/' || strchr(argv[0], '/') == NULL) {
985
* Leave alone if it is an absolute path, or if it does
986
* not contain a '/' in which case we need to find it in
987
* the path, like execvp(3) and the shells do.
992
* A relative path, canonicalize it.
994
p1 = realpath(argv[0], mdpath);
995
if (!p1 || *p1 != '/' || stat(p1, &sb) < 0) {
996
p1 = argv[0]; /* realpath failed */
999
Var_Set("MAKE", p1, VAR_GLOBAL, 0);
1000
Var_Set(".MAKE", p1, VAR_GLOBAL, 0);
1001
Var_Set(MAKEFLAGS, "", VAR_GLOBAL, 0);
1002
Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL, 0);
1003
Var_Set("MFLAGS", "", VAR_GLOBAL, 0);
1004
Var_Set(".ALLTARGETS", "", VAR_GLOBAL, 0);
1005
/* some makefiles need to know this */
1006
Var_Set(MAKE_LEVEL ".ENV", MAKE_LEVEL_ENV, VAR_CMD, 0);
1009
* Set some other useful macros
1014
makelevel = ((ep = getenv(MAKE_LEVEL_ENV)) && *ep) ? atoi(ep) : 0;
1017
snprintf(tmp, sizeof(tmp), "%d", makelevel);
1018
Var_Set(MAKE_LEVEL, tmp, VAR_GLOBAL, 0);
1019
snprintf(tmp, sizeof(tmp), "%u", myPid);
1020
Var_Set(".MAKE.PID", tmp, VAR_GLOBAL, 0);
1021
snprintf(tmp, sizeof(tmp), "%u", getppid());
1022
Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL, 0);
1024
if (makelevel > 0) {
1026
snprintf(pn, sizeof(pn), "%s[%d]", progname, makelevel);
1027
progname = bmake_strdup(pn);
1034
* First snag any flags out of the MAKE environment variable.
1035
* (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
1036
* in a different format).
1039
p1 = explode(getenv("MAKEFLAGS"));
1040
Main_ParseArgLine(p1);
1043
Main_ParseArgLine(getenv("MAKE"));
1047
* Find where we are (now).
1048
* We take care of PWD for the automounter below...
1050
if (getcwd(curdir, MAXPATHLEN) == NULL) {
1051
(void)fprintf(stderr, "%s: getcwd: %s.\n",
1052
progname, strerror(errno));
1056
MainParseArgs(argc, argv);
1059
printf("%s: Entering directory `%s'\n", progname, curdir);
1062
* Verify that cwd is sane.
1064
if (stat(curdir, &sa) == -1) {
1065
(void)fprintf(stderr, "%s: %s: %s.\n",
1066
progname, curdir, strerror(errno));
1071
* All this code is so that we know where we are when we start up
1072
* on a different machine with pmake.
1073
* Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
1074
* since the value of curdir can vary depending on how we got
1075
* here. Ie sitting at a shell prompt (shell that provides $PWD)
1076
* or via subdir.mk in which case its likely a shell which does
1078
* So, to stop it breaking this case only, we ignore PWD if
1079
* MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
1081
#ifndef NO_PWD_OVERRIDE
1085
if ((pwd = getenv("PWD")) != NULL &&
1086
getenv("MAKEOBJDIRPREFIX") == NULL) {
1087
const char *makeobjdir = getenv("MAKEOBJDIR");
1089
if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
1090
if (stat(pwd, &sb) == 0 &&
1091
sa.st_ino == sb.st_ino &&
1092
sa.st_dev == sb.st_dev)
1093
(void)strncpy(curdir, pwd, MAXPATHLEN);
1098
Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0);
1101
* Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
1102
* MAKEOBJDIR is set in the environment, try only that value
1103
* and fall back to .CURDIR if it does not exist.
1105
* Otherwise, try _PATH_OBJDIR.MACHINE, _PATH_OBJDIR, and
1106
* finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
1107
* of these paths exist, just use .CURDIR.
1110
(void)Main_SetObjdir(curdir);
1112
if ((path = getenv("MAKEOBJDIRPREFIX")) != NULL) {
1113
(void)snprintf(mdpath, MAXPATHLEN, "%s%s", path, curdir);
1114
(void)Main_SetObjdir(mdpath);
1115
} else if ((path = getenv("MAKEOBJDIR")) != NULL) {
1116
(void)Main_SetObjdir(path);
1118
(void)snprintf(mdpath, MAXPATHLEN, "%s.%s", _PATH_OBJDIR, machine);
1119
if (!Main_SetObjdir(mdpath) && !Main_SetObjdir(_PATH_OBJDIR)) {
1120
(void)snprintf(mdpath, MAXPATHLEN, "%s%s",
1121
_PATH_OBJDIRPREFIX, curdir);
1122
(void)Main_SetObjdir(mdpath);
1127
* Be compatible if user did not specify -j and did not explicitly
1128
* turned compatibility on
1130
if (!compatMake && !forceJobs) {
1135
* Initialize archive, target and suffix modules in preparation for
1136
* parsing the makefile(s)
1141
Trace_Init(tracefile);
1146
Trace_Log(MAKESTART, NULL);
1149
* Set up the .TARGETS variable to contain the list of targets to be
1150
* created. If none specified, make the variable empty -- the parser
1151
* will fill the thing in with the default or .MAIN target.
1153
if (!Lst_IsEmpty(create)) {
1156
for (ln = Lst_First(create); ln != NULL;
1157
ln = Lst_Succ(ln)) {
1158
char *name = (char *)Lst_Datum(ln);
1160
Var_Append(".TARGETS", name, VAR_GLOBAL);
1163
Var_Set(".TARGETS", "", VAR_GLOBAL, 0);
1167
* If no user-supplied system path was given (through the -m option)
1168
* add the directories from the DEFSYSPATH (more than one may be given
1169
* as dir1:...:dirn) to the system include path.
1171
if (syspath == NULL || *syspath == '\0')
1172
syspath = defsyspath;
1174
syspath = bmake_strdup(syspath);
1176
for (start = syspath; *start != '\0'; start = cp) {
1177
for (cp = start; *cp != '\0' && *cp != ':'; cp++)
1182
/* look for magic parent directory search string */
1183
if (strncmp(".../", start, 4) != 0) {
1184
(void)Dir_AddDir(defIncPath, start);
1186
if (Dir_FindHereOrAbove(curdir, start+4,
1187
found_path, sizeof(found_path))) {
1188
(void)Dir_AddDir(defIncPath, found_path);
1192
if (syspath != defsyspath)
1196
* Read in the built-in rules first, followed by the specified
1197
* makefile, if it was (makefile != NULL), or the default
1198
* makefile and Makefile, in that order, if it wasn't.
1203
sysMkPath = Lst_Init(FALSE);
1204
Dir_Expand(_PATH_DEFSYSMK,
1205
Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
1207
if (Lst_IsEmpty(sysMkPath))
1208
Fatal("%s: no system rules (%s).", progname,
1210
ln = Lst_Find(sysMkPath, NULL, ReadMakefile);
1212
Fatal("%s: cannot open %s.", progname,
1213
(char *)Lst_Datum(ln));
1216
if (!Lst_IsEmpty(makefiles)) {
1219
ln = Lst_Find(makefiles, NULL, ReadAllMakefiles);
1221
Fatal("%s: cannot open %s.", progname,
1222
(char *)Lst_Datum(ln));
1224
p1 = Var_Subst(NULL, "${" MAKEFILE_PREFERENCE "}",
1227
(void)str2Lst_Append(makefiles, p1, NULL);
1228
(void)Lst_Find(makefiles, NULL, ReadMakefile);
1233
/* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1234
if (!noBuiltins || !printVars) {
1235
makeDependfile = Var_Subst(NULL, "${.MAKE.DEPENDFILE:T}",
1237
doing_depend = TRUE;
1238
(void)ReadMakefile(makeDependfile, NULL);
1239
doing_depend = FALSE;
1244
Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
1249
Job_ServerStart(maxJobTokens, jp_0, jp_1);
1251
fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1252
jp_0, jp_1, maxJobs, maxJobTokens, compatMake);
1254
Main_ExportMAKEFLAGS(TRUE); /* initial export */
1257
* For compatibility, look at the directories in the VPATH variable
1258
* and add them to the search path, if the variable is defined. The
1259
* variable's value is in the same format as the PATH envariable, i.e.
1260
* <directory>:<directory>:<directory>...
1262
if (Var_Exists("VPATH", VAR_CMD)) {
1265
* GCC stores string constants in read-only memory, but
1266
* Var_Subst will want to write this thing, so store it
1269
static char VPATH[] = "${VPATH}";
1271
vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
1274
/* skip to end of directory */
1275
for (cp = path; *cp != ':' && *cp != '\0'; cp++)
1277
/* Save terminator character so know when to stop */
1280
/* Add directory to search path */
1281
(void)Dir_AddDir(dirSearchPath, path);
1284
} while (savec == ':');
1289
* Now that all search paths have been read for suffixes et al, it's
1290
* time to add the default search path to their lists...
1295
* Propagate attributes through :: dependency lists.
1299
/* print the initial graph, if the user requested it */
1303
/* print the values of any variables requested by the user */
1311
expandVars = getBoolean(".MAKE.EXPAND_VARIABLES", FALSE);
1312
for (ln = Lst_First(variables); ln != NULL;
1313
ln = Lst_Succ(ln)) {
1314
char *var = (char *)Lst_Datum(ln);
1317
if (strchr(var, '$')) {
1318
value = p1 = Var_Subst(NULL, var, VAR_GLOBAL, 0);
1319
} else if (expandVars) {
1322
if (snprintf(tmp, sizeof(tmp), "${%s}", var) >= (int)(sizeof(tmp)))
1323
Fatal("%s: variable name too big: %s",
1325
value = p1 = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1327
value = Var_Value(var, VAR_GLOBAL, &p1);
1329
printf("%s\n", value ? value : "");
1335
* Have now read the entire graph and need to make a list of
1336
* targets to create. If none was given on the command line,
1337
* we consult the parsing module to find the main target(s)
1340
if (Lst_IsEmpty(create))
1341
targs = Parse_MainName();
1343
targs = Targ_FindList(create, TARG_CREATE);
1347
* Initialize job module before traversing the graph
1348
* now that any .BEGIN and .END targets have been read.
1349
* This is done only if the -q flag wasn't given
1350
* (to prevent the .BEGIN from being executed should
1358
/* Traverse the graph, checking on all the targets */
1359
outOfDate = Make_Run(targs);
1362
* Compat_Init will take care of creating all the
1363
* targets as well as initializing the module.
1370
Lst_Destroy(targs, NULL);
1371
Lst_Destroy(variables, NULL);
1372
Lst_Destroy(makefiles, NULL);
1373
Lst_Destroy(create, (FreeProc *)free);
1376
/* print the graph now it's been processed if the user requested it */
1380
Trace_Log(MAKEEND, 0);
1383
printf("%s: Leaving directory `%s'\n", progname, curdir);
1394
return outOfDate ? 1 : 0;
1399
* Open and parse the given makefile.
1402
* 0 if ok. -1 if couldn't open file.
1408
ReadMakefile(const void *p, const void *q MAKE_ATTR_UNUSED)
1410
const char *fname = p; /* makefile to read */
1412
size_t len = MAXPATHLEN;
1413
char *name, *path = bmake_malloc(len);
1415
if (!strcmp(fname, "-")) {
1416
Parse_File(NULL /*stdin*/, -1);
1417
Var_Set("MAKEFILE", "", VAR_INTERNAL, 0);
1419
/* if we've chdir'd, rebuild the path name */
1420
if (strcmp(curdir, objdir) && *fname != '/') {
1421
size_t plen = strlen(curdir) + strlen(fname) + 2;
1423
path = bmake_realloc(path, len = 2 * plen);
1425
(void)snprintf(path, len, "%s/%s", curdir, fname);
1426
fd = open(path, O_RDONLY);
1432
/* If curdir failed, try objdir (ala .depend) */
1433
plen = strlen(objdir) + strlen(fname) + 2;
1435
path = bmake_realloc(path, len = 2 * plen);
1436
(void)snprintf(path, len, "%s/%s", objdir, fname);
1437
fd = open(path, O_RDONLY);
1443
fd = open(fname, O_RDONLY);
1447
/* look in -I and system include directories. */
1448
name = Dir_FindFile(fname, parseIncPath);
1450
name = Dir_FindFile(fname,
1451
Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1452
if (!name || (fd = open(name, O_RDONLY)) == -1) {
1460
* set the MAKEFILE variable desired by System V fans -- the
1461
* placement of the setting here means it gets set to the last
1462
* makefile specified, as it is set by SysV make.
1466
Var_Set("MAKEFILE", fname, VAR_INTERNAL, 0);
1467
Parse_File(fname, fd);
1477
* Execute the command in cmd, and return the output of that command
1481
* A string containing the output of the command, or the empty string
1482
* If errnum is not NULL, it contains the reason for the command failure
1485
* The string must be freed by the caller.
1488
Cmd_Exec(const char *cmd, const char **errnum)
1490
const char *args[4]; /* Args for invoking the shell */
1491
int fds[2]; /* Pipe streams */
1492
int cpid; /* Child PID */
1493
int pid; /* PID from wait() */
1494
char *res; /* result */
1495
WAIT_T status; /* command exit status */
1496
Buffer buf; /* buffer to store the result */
1506
* Set up arguments for shell
1508
args[0] = shellName;
1514
* Open a pipe for fetching its output
1516
if (pipe(fds) == -1) {
1517
*errnum = "Couldn't create pipe for \"%s\"";
1524
switch (cpid = vFork()) {
1527
* Close input side of pipe
1529
(void)close(fds[0]);
1532
* Duplicate the output stream to the shell's output, then
1533
* shut the extra thing down. Note we don't fetch the error
1534
* stream...why not? Why?
1536
(void)dup2(fds[1], 1);
1537
(void)close(fds[1]);
1541
(void)execv(shellPath, UNCONST(args));
1546
*errnum = "Couldn't exec \"%s\"";
1551
* No need for the writing half
1553
(void)close(fds[1]);
1558
char result[BUFSIZ];
1559
cc = read(fds[0], result, sizeof(result));
1561
Buf_AddBytes(&buf, cc, result);
1563
while (cc > 0 || (cc == -1 && errno == EINTR));
1566
* Close the input side of the pipe.
1568
(void)close(fds[0]);
1571
* Wait for the process to exit.
1573
while(((pid = waitpid(cpid, &status, 0)) != cpid) && (pid >= 0)) {
1574
JobReapChild(pid, status, FALSE);
1577
cc = Buf_Size(&buf);
1578
res = Buf_Destroy(&buf, FALSE);
1581
*errnum = "Couldn't read shell's output for \"%s\"";
1583
if (WIFSIGNALED(status))
1584
*errnum = "\"%s\" exited on a signal";
1585
else if (WEXITSTATUS(status) != 0)
1586
*errnum = "\"%s\" returned non-zero status";
1589
* Null-terminate the result, convert newlines to spaces and
1590
* install it in the variable.
1595
if (cc > 0 && *--cp == '\n') {
1597
* A final newline is just stripped
1611
res = bmake_malloc(1);
1618
* Print an error message given its format.
1624
* The message is printed.
1628
Error(const char *fmt, ...)
1633
err_file = debug_file;
1634
if (err_file == stdout)
1636
(void)fflush(stdout);
1639
fprintf(err_file, "%s: ", progname);
1640
(void)vfprintf(err_file, fmt, ap);
1642
(void)fprintf(err_file, "\n");
1643
(void)fflush(err_file);
1644
if (err_file == stderr)
1652
* Produce a Fatal error message. If jobs are running, waits for them
1663
Fatal(const char *fmt, ...)
1671
(void)fflush(stdout);
1672
(void)vfprintf(stderr, fmt, ap);
1674
(void)fprintf(stderr, "\n");
1675
(void)fflush(stderr);
1677
PrintOnError(NULL, NULL);
1679
if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1681
Trace_Log(MAKEERROR, 0);
1682
exit(2); /* Not 1 so -q can distinguish error */
1687
* Major exception once jobs are being created. Kills all jobs, prints
1688
* a message and exits.
1694
* All children are killed indiscriminately and the program Lib_Exits
1698
Punt(const char *fmt, ...)
1703
(void)fflush(stdout);
1704
(void)fprintf(stderr, "%s: ", progname);
1705
(void)vfprintf(stderr, fmt, ap);
1707
(void)fprintf(stderr, "\n");
1708
(void)fflush(stderr);
1710
PrintOnError(NULL, NULL);
1717
* Exit without giving a message.
1732
Trace_Log(MAKEERROR, 0);
1733
exit(2); /* Not 1, so -q can distinguish error */
1738
* Called when aborting due to errors in child shell to signal
1749
/* number of errors encountered in Make_Make */
1751
Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1756
* Remove a file carefully, avoiding directories.
1759
eunlink(const char *file)
1763
if (lstat(file, &st) == -1)
1766
if (S_ISDIR(st.st_mode)) {
1770
return unlink(file);
1775
* Print why exec failed, avoiding stdio.
1778
execError(const char *af, const char *av)
1782
struct iovec iov[8];
1784
(void)(iov[i].iov_base = UNCONST(s), \
1785
iov[i].iov_len = strlen(iov[i].iov_base), \
1788
#define IOADD(s) (void)write(2, s, strlen(s))
1796
IOADD(") failed (");
1797
IOADD(strerror(errno));
1801
while (writev(2, iov, 8) == -1 && errno == EAGAIN)
1808
* exit with usage message
1814
if ((p = strchr(progname, '[')) != NULL)
1817
(void)fprintf(stderr,
1818
"usage: %s [-BeikNnqrstWwX] \n\
1819
[-C directory] [-D variable] [-d flags] [-f makefile]\n\
1820
[-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1821
[-V variable] [variable=value] [target ...]\n", progname);
1827
PrintAddr(void *a, void *b)
1829
printf("%lx ", (unsigned long) a);
1836
PrintOnError(GNode *gn, const char *s)
1838
static GNode *en = NULL;
1845
printf("\n%s: stopped in %s\n", progname, curdir);
1848
return; /* we've been here! */
1851
* We can print this even if there is no .ERROR target.
1853
Var_Set(".ERROR_TARGET", gn->name, VAR_GLOBAL, 0);
1855
strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1857
cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1864
* Finally, see if there is a .ERROR target, and run it if so.
1866
en = Targ_FindNode(".ERROR", TARG_NOCREATE);
1868
en->type |= OP_SPECIAL;
1869
Compat_Make(en, en);
1874
Main_ExportMAKEFLAGS(Boolean first)
1876
static int once = 1;
1884
strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1886
s = Var_Subst(NULL, tmp, VAR_CMD, 0);
1889
setenv("MAKEFLAGS", s, 1);
1891
setenv("MAKE", s, 1);
1899
static char *tmpdir = NULL;
1905
* Honor $TMPDIR but only if it is valid.
1906
* Ensure it ends with /.
1908
tmpdir = Var_Subst(NULL, "${TMPDIR:tA:U" _PATH_TMP "}/", VAR_GLOBAL, 0);
1909
if (stat(tmpdir, &st) < 0 || !S_ISDIR(st.st_mode)) {
1911
tmpdir = bmake_strdup(_PATH_TMP);
1918
* Create and open a temp file using "pattern".
1919
* If "fnamep" is provided set it to a copy of the filename created.
1920
* Otherwise unlink the file once open.
1923
mkTempFile(const char *pattern, char **fnamep)
1925
static char *tmpdir = NULL;
1926
char tfile[MAXPATHLEN];
1932
tmpdir = getTmpdir();
1933
if (pattern[0] == '/') {
1934
snprintf(tfile, sizeof(tfile), "%s", pattern);
1936
snprintf(tfile, sizeof(tfile), "%s%s", tmpdir, pattern);
1938
if ((fd = mkstemp(tfile)) < 0)
1939
Punt("Could not create temporary file %s: %s", tfile, strerror(errno));
1941
*fnamep = bmake_strdup(tfile);
1943
unlink(tfile); /* we just want the descriptor */
1950
* Return a Boolean based on setting of a knob.
1952
* If the knob is not set, the supplied default is the return value.
1953
* If set, anything that looks or smells like "No", "False", "Off", "0" etc,
1954
* is FALSE, otherwise TRUE.
1957
getBoolean(const char *name, Boolean bf)
1962
if (snprintf(tmp, sizeof(tmp), "${%s:tl}", name) < (int)(sizeof(tmp))) {
1963
cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1967
case '\0': /* not set - the default wins */