1
/* $NetBSD: main.c,v 1.111 2005/06/24 02:53:27 lukem 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.111 2005/06/24 02:53:27 lukem Exp $";
74
#include <sys/cdefs.h>
76
__COPYRIGHT("@(#) Copyright (c) 1988, 1989, 1990, 1993\n\
77
The Regents of the University of California. All rights reserved.\n");
82
static char sccsid[] = "@(#)main.c 8.3 (Berkeley) 3/19/94";
84
__RCSID("$NetBSD: main.c,v 1.111 2005/06/24 02:53:27 lukem 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 maxLocal; /* -L argument */
160
Boolean compatMake; /* -B argument */
161
Boolean debug; /* -d flag */
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 usePipes; /* !-P 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
Boolean varNoExportEnv; /* -X flag */
175
static Boolean jobsRunning; /* TRUE if the jobs might be running */
176
static const char * tracefile;
177
static char * Check_Cwd_av(int, char **, int);
178
static void MainParseArgs(int, char **);
179
static int ReadMakefile(ClientData, ClientData);
180
static void usage(void);
182
static char curdir[MAXPATHLEN + 1]; /* startup directory */
183
static char objdir[MAXPATHLEN + 1]; /* where we chdir'ed to */
184
char *progname; /* the program name */
186
Boolean forceJobs = FALSE;
188
extern Lst parseIncPath;
192
* Parse a given argument vector. Called from main() and from
193
* Main_ParseArgLine() when the .MAKEFLAGS target is used.
195
* XXX: Deal with command line overriding .MAKEFLAGS in makefile
201
* Various global and local flags will be set depending on the flags
205
MainParseArgs(int argc, char **argv)
211
const char *getopt_def;
213
Boolean inOption, dashDash = FALSE;
214
char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
217
# define OPTFLAGS "BD:I:J:L:NPST:V:WXd:ef:ij:km:nqrst"
219
# define OPTFLAGS "BD:I:J:NPST:V:WXd:ef:ij:km:nqrst"
222
#define optarg argvalue
223
/* Can't actually use getopt(3) because rescanning is not portable */
225
getopt_def = OPTFLAGS;
243
if (c != '-' || dashDash)
248
/* '-' found at some earlier point */
249
getopt_spec = strchr(getopt_def, c);
250
if(c != '\0' && getopt_spec != NULL && getopt_spec[1] == ':') {
251
/* -<something> found, and <something> should have an arg */
255
if(*argvalue == '\0') {
257
(void)fprintf(stderr,
258
"%s: option requires "
259
"an argument -- %c\n",
276
Var_Append(MAKEFLAGS, "-B", VAR_GLOBAL);
279
Var_Set(optarg, "1", VAR_GLOBAL, 0);
280
Var_Append(MAKEFLAGS, "-D", VAR_GLOBAL);
281
Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
284
Parse_AddIncludeDir(optarg);
285
Var_Append(MAKEFLAGS, "-I", VAR_GLOBAL);
286
Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
289
if (sscanf(optarg, "%d,%d", &job_pipe[0], &job_pipe[1]) != 2) {
290
/* backslash to avoid trigraph ??) */
291
(void)fprintf(stderr,
292
"%s: internal error -- J option malformed (%s?\?)\n",
296
if ((fcntl(job_pipe[0], F_GETFD, 0) < 0) ||
297
(fcntl(job_pipe[1], F_GETFD, 0) < 0)) {
299
(void)fprintf(stderr,
300
"%s: warning -- J descriptors were closed!\n",
307
Var_Append(MAKEFLAGS, "-J", VAR_GLOBAL);
308
Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
314
maxLocal = strtol(optarg, &p, 0);
315
if (*p != '\0' || maxLocal < 1) {
316
(void) fprintf(stderr, "%s: illegal argument to -L -- must be positive integer!\n",
320
Var_Append(MAKEFLAGS, "-L", VAR_GLOBAL);
321
Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
326
noRecursiveExecute = TRUE;
327
Var_Append(MAKEFLAGS, "-N", VAR_GLOBAL);
331
Var_Append(MAKEFLAGS, "-P", VAR_GLOBAL);
335
Var_Append(MAKEFLAGS, "-S", VAR_GLOBAL);
338
tracefile = estrdup(optarg);
339
Var_Append(MAKEFLAGS, "-T", VAR_GLOBAL);
340
Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
344
(void)Lst_AtEnd(variables, (ClientData)optarg);
345
Var_Append(MAKEFLAGS, "-V", VAR_GLOBAL);
346
Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
349
parseWarnFatal = TRUE;
352
varNoExportEnv = TRUE;
353
Var_Append(MAKEFLAGS, "-X", VAR_GLOBAL);
356
char *modules = optarg;
358
for (; *modules; ++modules)
373
debug |= DEBUG_ERROR;
379
if (modules[1] == '1') {
380
debug |= DEBUG_GRAPH1;
383
else if (modules[1] == '2') {
384
debug |= DEBUG_GRAPH2;
387
else if (modules[1] == '3') {
388
debug |= DEBUG_GRAPH3;
399
debug |= DEBUG_SCRIPT;
411
debug |= DEBUG_SHELL;
414
(void)fprintf(stderr,
415
"%s: illegal argument to d option -- %c\n",
419
Var_Append(MAKEFLAGS, "-d", VAR_GLOBAL);
420
Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
424
checkEnvFirst = TRUE;
425
Var_Append(MAKEFLAGS, "-e", VAR_GLOBAL);
428
(void)Lst_AtEnd(makefiles, (ClientData)optarg);
432
Var_Append(MAKEFLAGS, "-i", VAR_GLOBAL);
436
maxJobs = strtol(optarg, &p, 0);
437
if (*p != '\0' || maxJobs < 1) {
438
(void) fprintf(stderr, "%s: illegal argument to -j -- must be positive integer!\n",
445
Var_Append(MAKEFLAGS, "-j", VAR_GLOBAL);
446
Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
450
Var_Append(MAKEFLAGS, "-k", VAR_GLOBAL);
453
/* look for magic parent directory search string */
454
if (strncmp(".../", optarg, 4) == 0) {
455
if (!Dir_FindHereOrAbove(curdir, optarg+4,
456
found_path, sizeof(found_path)))
457
break; /* nothing doing */
458
(void) Dir_AddDir(sysIncPath, found_path);
461
(void) Dir_AddDir(sysIncPath, optarg);
463
Var_Append(MAKEFLAGS, "-m", VAR_GLOBAL);
464
Var_Append(MAKEFLAGS, optarg, VAR_GLOBAL);
468
Var_Append(MAKEFLAGS, "-n", VAR_GLOBAL);
472
/* Kind of nonsensical, wot? */
473
Var_Append(MAKEFLAGS, "-q", VAR_GLOBAL);
477
Var_Append(MAKEFLAGS, "-r", VAR_GLOBAL);
481
Var_Append(MAKEFLAGS, "-s", VAR_GLOBAL);
485
Var_Append(MAKEFLAGS, "-t", VAR_GLOBAL);
501
* See if the rest of the arguments are variable assignments and
502
* perform them if so. Else take them to be targets and stuff them
503
* on the end of the "create" list.
505
for (; argc > 1; ++argv, --argc)
506
if (Parse_IsVar(argv[1])) {
507
Parse_DoVar(argv[1], VAR_CMD);
510
Punt("illegal (null) argument.");
511
if (*argv[1] == '-' && !dashDash)
513
(void)Lst_AtEnd(create, (ClientData)estrdup(argv[1]));
518
* Main_ParseArgLine --
519
* Used by the parse module when a .MFLAGS or .MAKEFLAGS target
520
* is encountered and by main() when reading the .MAKEFLAGS envariable.
521
* Takes a line of arguments and breaks it into its
522
* component words and passes those words and the number of them to the
523
* MainParseArgs function.
524
* The line should have all its leading whitespace removed.
527
* line Line to fracture
533
* Only those that come from the various arguments.
536
Main_ParseArgLine(char *line)
538
char **argv; /* Manufactured argument vector */
539
int argc; /* Number of arguments in argv */
540
char *args; /* Space used by the args */
542
char *argv0 = Var_Value(".MAKE", VAR_GLOBAL, &p1);
547
for (; *line == ' '; ++line)
552
buf = emalloc(len = strlen(line) + strlen(argv0) + 2);
553
(void)snprintf(buf, len, "%s %s", argv0, line);
557
argv = brk_string(buf, &argc, TRUE, &args);
559
MainParseArgs(argc, argv);
566
Main_SetObjdir(const char *path)
570
char buf[MAXPATHLEN + 1];
573
/* expand variable substitutions */
574
if (strchr(path, '$') != 0) {
575
snprintf(buf, MAXPATHLEN, "%s", path);
576
path = p = Var_Subst(NULL, buf, VAR_GLOBAL, 0);
579
if (path[0] != '/') {
580
snprintf(buf, MAXPATHLEN, "%s/%s", curdir, path);
584
/* look for the directory and try to chdir there */
585
if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
587
(void)fprintf(stderr, "make warning: %s: %s.\n",
588
path, strerror(errno));
590
strncpy(objdir, path, MAXPATHLEN);
591
Var_Set(".OBJDIR", objdir, VAR_GLOBAL, 0);
592
setenv("PWD", objdir, 1);
606
* The main function, for obvious reasons. Initializes variables
607
* and a few modules, then parses the arguments give it in the
608
* environment and on the command line. Reads the system makefile
609
* followed by either Makefile, makefile or the file given by the
610
* -f argument. Sets the .MAKEFLAGS PMake variable based on all the
611
* flags it has received by then uses either the Make or the Compat
612
* module to create the initial list of targets.
615
* If -q was given, exits -1 if anything was out-of-date. Else it exits
619
* The program exits when done. Targets are created. etc. etc. etc.
622
main(int argc, char **argv)
624
Lst targs; /* target nodes to create -- passed to Make_Init */
625
Boolean outOfDate = TRUE; /* FALSE if all targets up to date */
627
char *p1, *path, *pwd;
628
char mdpath[MAXPATHLEN];
629
char *machine = getenv("MACHINE");
630
const char *machine_arch = getenv("MACHINE_ARCH");
631
char *syspath = getenv("MAKESYSPATH");
632
Lst sysMkPath; /* Path of sys.mk */
633
char *cp = NULL, *start;
634
/* avoid faults on read-only strings */
635
static char defsyspath[] = _PATH_DEFSYSPATH;
636
char found_path[MAXPATHLEN + 1]; /* for searching for sys.mk */
637
struct timeval rightnow; /* to initialize random seed */
640
* Set the seed to produce a different random sequences
641
* on each program execution.
643
gettimeofday(&rightnow, NULL);
644
srandom(rightnow.tv_sec + rightnow.tv_usec);
646
if ((progname = strrchr(argv[0], '/')) != NULL)
652
* get rid of resource limit on file descriptors
656
if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
657
rl.rlim_cur != rl.rlim_max) {
658
rl.rlim_cur = rl.rlim_max;
659
(void) setrlimit(RLIMIT_NOFILE, &rl);
664
* Find where we are and take care of PWD for the automounter...
665
* All this code is so that we know where we are when we start up
666
* on a different machine with pmake.
668
if (getcwd(curdir, MAXPATHLEN) == NULL) {
669
(void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
673
if (stat(curdir, &sa) == -1) {
674
(void)fprintf(stderr, "%s: %s: %s.\n",
675
progname, curdir, strerror(errno));
680
* Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
681
* since the value of curdir can very depending on how we got
682
* here. Ie sitting at a shell prompt (shell that provides $PWD)
683
* or via subdir.mk in which case its likely a shell which does
685
* So, to stop it breaking this case only, we ignore PWD if
686
* MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
688
if ((pwd = getenv("PWD")) != NULL && getenv("MAKEOBJDIRPREFIX") == NULL) {
689
const char *makeobjdir = getenv("MAKEOBJDIR");
691
if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
692
if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
693
sa.st_dev == sb.st_dev)
694
(void) strncpy(curdir, pwd, MAXPATHLEN);
699
* Get the name of this type of MACHINE from utsname
700
* so we can share an executable for similar machines.
701
* (i.e. m68k: amiga hp300, mac68k, sun3, ...)
703
* Note that both MACHINE and MACHINE_ARCH are decided at
708
struct utsname utsname;
710
if (uname(&utsname) == -1) {
711
(void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
715
machine = utsname.machine;
718
machine = MAKE_MACHINE;
727
#ifdef MAKE_MACHINE_ARCH
728
machine_arch = MAKE_MACHINE_ARCH;
730
machine_arch = "unknown";
733
machine_arch = MACHINE_ARCH;
738
* Just in case MAKEOBJDIR wants us to do something tricky.
740
Var_Init(); /* Initialize the lists of variables for
741
* parsing arguments */
742
Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0);
743
Var_Set("MACHINE", machine, VAR_GLOBAL, 0);
744
Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL, 0);
746
Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL, 0);
748
Var_Set(".newline", "\n", VAR_GLOBAL, 0); /* handy for :@ loops */
751
* Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
752
* MAKEOBJDIR is set in the environment, try only that value
753
* and fall back to .CURDIR if it does not exist.
755
* Otherwise, try _PATH_OBJDIR.MACHINE, _PATH_OBJDIR, and
756
* finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
757
* of these paths exist, just use .CURDIR.
760
(void) Main_SetObjdir(curdir);
762
if ((path = getenv("MAKEOBJDIRPREFIX")) != NULL) {
763
(void) snprintf(mdpath, MAXPATHLEN, "%s%s", path, curdir);
764
(void) Main_SetObjdir(mdpath);
765
} else if ((path = getenv("MAKEOBJDIR")) != NULL) {
766
(void) Main_SetObjdir(path);
768
(void) snprintf(mdpath, MAXPATHLEN, "%s.%s", _PATH_OBJDIR, machine);
769
if (!Main_SetObjdir(mdpath) && !Main_SetObjdir(_PATH_OBJDIR)) {
770
(void) snprintf(mdpath, MAXPATHLEN, "%s%s",
771
_PATH_OBJDIRPREFIX, curdir);
772
(void) Main_SetObjdir(mdpath);
776
create = Lst_Init(FALSE);
777
makefiles = Lst_Init(FALSE);
779
variables = Lst_Init(FALSE);
780
beSilent = FALSE; /* Print commands as executed */
781
ignoreErrors = FALSE; /* Pay attention to non-zero returns */
782
noExecute = FALSE; /* Execute all commands */
783
noRecursiveExecute = FALSE; /* Execute all .MAKE targets */
784
keepgoing = FALSE; /* Stop on error */
785
allPrecious = FALSE; /* Remove targets when interrupted */
786
queryFlag = FALSE; /* This is not just a check-run */
787
noBuiltins = FALSE; /* Read the built-in rules */
788
touchFlag = FALSE; /* Actually update targets */
789
usePipes = TRUE; /* Catch child output in pipes */
790
debug = 0; /* No debug verbosity, please. */
793
maxLocal = DEFMAXLOCAL; /* Set default local max concurrency */
795
maxJobs = DEFMAXJOBS; /* Set default max concurrency */
799
compatMake = FALSE; /* No compat mode */
803
* Initialize the parsing, directory and variable modules to prepare
804
* for the reading of inclusion paths and variable settings on the
809
* Initialize various variables.
810
* MAKE also gets this name, for compatibility
811
* .MAKEFLAGS gets set to the empty string just in case.
812
* MFLAGS also gets initialized empty, for compatibility.
815
Var_Set("MAKE", argv[0], VAR_GLOBAL, 0);
816
Var_Set(".MAKE", argv[0], VAR_GLOBAL, 0);
817
Var_Set(MAKEFLAGS, "", VAR_GLOBAL, 0);
818
Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL, 0);
819
Var_Set("MFLAGS", "", VAR_GLOBAL, 0);
820
Var_Set(".ALLTARGETS", "", VAR_GLOBAL, 0);
823
* First snag any flags out of the MAKE environment variable.
824
* (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
825
* in a different format).
828
Main_ParseArgLine(getenv("MAKEFLAGS"));
830
Main_ParseArgLine(getenv("MAKE"));
833
MainParseArgs(argc, argv);
836
* Be compatible if user did not specify -j and did not explicitly
837
* turned compatibility on
839
if (!compatMake && !forceJobs) {
844
* Initialize archive, target and suffix modules in preparation for
845
* parsing the makefile(s)
850
Trace_Init(tracefile);
855
Trace_Log(MAKESTART, NULL);
858
* Set up the .TARGETS variable to contain the list of targets to be
859
* created. If none specified, make the variable empty -- the parser
860
* will fill the thing in with the default or .MAIN target.
862
if (!Lst_IsEmpty(create)) {
865
for (ln = Lst_First(create); ln != NILLNODE;
867
char *name = (char *)Lst_Datum(ln);
869
Var_Append(".TARGETS", name, VAR_GLOBAL);
872
Var_Set(".TARGETS", "", VAR_GLOBAL, 0);
876
* If no user-supplied system path was given (through the -m option)
877
* add the directories from the DEFSYSPATH (more than one may be given
878
* as dir1:...:dirn) to the system include path.
880
if (syspath == NULL || *syspath == '\0')
881
syspath = defsyspath;
883
syspath = strdup(syspath);
885
for (start = syspath; *start != '\0'; start = cp) {
886
for (cp = start; *cp != '\0' && *cp != ':'; cp++)
891
/* look for magic parent directory search string */
892
if (strncmp(".../", start, 4) != 0) {
893
(void) Dir_AddDir(defIncPath, start);
895
if (Dir_FindHereOrAbove(curdir, start+4,
896
found_path, sizeof(found_path))) {
897
(void) Dir_AddDir(defIncPath, found_path);
901
if (syspath != defsyspath)
905
* Read in the built-in rules first, followed by the specified
906
* makefile, if it was (makefile != (char *) NULL), or the default
907
* makefile and Makefile, in that order, if it wasn't.
912
sysMkPath = Lst_Init(FALSE);
913
Dir_Expand(_PATH_DEFSYSMK,
914
Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
916
if (Lst_IsEmpty(sysMkPath))
917
Fatal("%s: no system rules (%s).", progname,
919
ln = Lst_Find(sysMkPath, (ClientData)NULL, ReadMakefile);
921
Fatal("%s: cannot open %s.", progname,
922
(char *)Lst_Datum(ln));
925
if (!Lst_IsEmpty(makefiles)) {
928
ln = Lst_Find(makefiles, (ClientData)NULL, ReadMakefile);
930
Fatal("%s: cannot open %s.", progname,
931
(char *)Lst_Datum(ln));
932
} else if (!ReadMakefile(UNCONST("makefile"), NULL))
933
(void)ReadMakefile(UNCONST("Makefile"), NULL);
935
(void)ReadMakefile(UNCONST(".depend"), NULL);
937
Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
941
if (!jobServer && !compatMake)
942
Job_ServerStart(maxJobs);
944
printf("job_pipe %d %d, maxjobs %d maxlocal %d compat %d\n", job_pipe[0], job_pipe[1], maxJobs,
945
maxLocal, compatMake);
947
Main_ExportMAKEFLAGS(TRUE); /* initial export */
949
Check_Cwd_av(0, NULL, 0); /* initialize it */
953
* For compatibility, look at the directories in the VPATH variable
954
* and add them to the search path, if the variable is defined. The
955
* variable's value is in the same format as the PATH envariable, i.e.
956
* <directory>:<directory>:<directory>...
958
if (Var_Exists("VPATH", VAR_CMD)) {
961
* GCC stores string constants in read-only memory, but
962
* Var_Subst will want to write this thing, so store it
965
static char VPATH[] = "${VPATH}";
967
vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
970
/* skip to end of directory */
971
for (cp = path; *cp != ':' && *cp != '\0'; cp++)
973
/* Save terminator character so know when to stop */
976
/* Add directory to search path */
977
(void) Dir_AddDir(dirSearchPath, path);
980
} while (savec == ':');
981
(void)free((Address)vpath);
985
* Now that all search paths have been read for suffixes et al, it's
986
* time to add the default search path to their lists...
991
* Propagate attributes through :: dependency lists.
995
/* print the initial graph, if the user requested it */
999
/* print the values of any variables requested by the user */
1003
for (ln = Lst_First(variables); ln != NILLNODE;
1004
ln = Lst_Succ(ln)) {
1005
char *var = (char *)Lst_Datum(ln);
1008
if (strchr(var, '$')) {
1009
value = p1 = Var_Subst(NULL, var, VAR_GLOBAL, 0);
1011
value = Var_Value(var, VAR_GLOBAL, &p1);
1013
printf("%s\n", value ? value : "");
1020
* Have now read the entire graph and need to make a list of targets
1021
* to create. If none was given on the command line, we consult the
1022
* parsing module to find the main target(s) to create.
1024
if (Lst_IsEmpty(create))
1025
targs = Parse_MainName();
1027
targs = Targ_FindList(create, TARG_CREATE);
1029
if (!compatMake && !printVars) {
1031
* Initialize job module before traversing the graph, now that
1032
* any .BEGIN and .END targets have been read. This is done
1033
* only if the -q flag wasn't given (to prevent the .BEGIN from
1034
* being executed should it exist).
1039
Job_Init(maxJobs, maxLocal);
1043
/* Traverse the graph, checking on all the targets */
1044
outOfDate = Make_Run(targs);
1045
} else if (!printVars) {
1047
* Compat_Init will take care of creating all the targets as
1048
* well as initializing the module.
1054
Lst_Destroy(targs, NOFREE);
1055
Lst_Destroy(variables, NOFREE);
1056
Lst_Destroy(makefiles, NOFREE);
1057
Lst_Destroy(create, (void (*)(ClientData))) free;
1060
/* print the graph now it's been processed if the user requested it */
1064
Trace_Log(MAKEEND, 0);
1075
if (queryFlag && outOfDate)
1083
* Open and parse the given makefile.
1086
* TRUE if ok. FALSE if couldn't open file.
1092
ReadMakefile(ClientData p, ClientData q __unused)
1094
char *fname = p; /* makefile to read */
1096
size_t len = MAXPATHLEN;
1097
char *name, *path = emalloc(len);
1100
if (!strcmp(fname, "-")) {
1101
Parse_File("(stdin)", stdin);
1102
Var_Set("MAKEFILE", "", VAR_GLOBAL, 0);
1104
setMAKEFILE = strcmp(fname, ".depend");
1106
/* if we've chdir'd, rebuild the path name */
1107
if (strcmp(curdir, objdir) && *fname != '/') {
1108
size_t plen = strlen(curdir) + strlen(fname) + 2;
1110
path = erealloc(path, len = 2 * plen);
1112
(void)snprintf(path, len, "%s/%s", curdir, fname);
1113
if ((stream = fopen(path, "r")) != NULL) {
1118
/* If curdir failed, try objdir (ala .depend) */
1119
plen = strlen(objdir) + strlen(fname) + 2;
1121
path = erealloc(path, len = 2 * plen);
1122
(void)snprintf(path, len, "%s/%s", objdir, fname);
1123
if ((stream = fopen(path, "r")) != NULL) {
1127
} else if ((stream = fopen(fname, "r")) != NULL)
1129
/* look in -I and system include directories. */
1130
name = Dir_FindFile(fname, parseIncPath);
1132
name = Dir_FindFile(fname,
1133
Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1134
if (!name || !(stream = fopen(name, "r"))) {
1140
* set the MAKEFILE variable desired by System V fans -- the
1141
* placement of the setting here means it gets set to the last
1142
* makefile specified, as it is set by SysV make.
1146
Var_Set("MAKEFILE", fname, VAR_GLOBAL, 0);
1147
Parse_File(fname, stream);
1148
(void)fclose(stream);
1156
* If MAKEOBJDIRPREFIX is in use, make ends up not in .CURDIR
1157
* in situations that would not arrise with ./obj (links or not).
1158
* This tends to break things like:
1163
* This function spots when ${.MAKE:T} or ${.MAKE} is a command (as
1164
* opposed to an argument) in a command line and if so returns
1165
* ${.CURDIR} so caller can chdir() so that the assumptions made by
1166
* the Makefile hold true.
1168
* If ${.MAKE} does not contain any '/', then ${.MAKE:T} is skipped.
1170
* The chdir() only happens in the child process, and does nothing if
1171
* MAKEOBJDIRPREFIX and MAKEOBJDIR are not in the environment so it
1172
* should not break anything. Also if NOCHECKMAKECHDIR is set we
1173
* do nothing - to ensure historic semantics can be retained.
1175
static int Check_Cwd_Off = 0;
1178
Check_Cwd_av(int ac, char **av, int copy)
1180
static char *make[4];
1181
static char *cur_dir = NULL;
1184
int is_cmd, next_cmd;
1191
if (make[0] == NULL) {
1192
if (Var_Exists("NOCHECKMAKECHDIR", VAR_GLOBAL)) {
1197
make[1] = Var_Value(".MAKE", VAR_GLOBAL, &cp);
1198
if ((make[0] = strrchr(make[1], '/')) == NULL) {
1204
cur_dir = Var_Value(".CURDIR", VAR_GLOBAL, &cp);
1206
if (ac == 0 || av == NULL)
1207
return NULL; /* initialization only */
1209
if (getenv("MAKEOBJDIR") == NULL &&
1210
getenv("MAKEOBJDIRPREFIX") == NULL)
1215
for (i = 0; i < ac; ++i) {
1219
cp = &(av[i])[n - 1];
1220
if (strspn(av[i], "|&;") == n) {
1223
} else if (*cp == ';' || *cp == '&' || *cp == '|' || *cp == ')') {
1228
} while (*cp == ';' || *cp == '&' || *cp == '|' ||
1229
*cp == ')' || *cp == '}') ;
1232
* XXX this should not happen.
1234
fprintf(stderr, "WARNING: raw arg ends in shell meta '%s'\n",
1241
if (*cp == ';' || *cp == '&' || *cp == '|')
1244
#ifdef check_cwd_debug
1245
fprintf(stderr, "av[%d] == %s '%s'",
1246
i, (is_cmd) ? "cmd" : "arg", av[i]);
1249
if (*cp == '(' || *cp == '{' ||
1250
*cp == ';' || *cp == '&' || *cp == '|') {
1253
} while (*cp == '(' || *cp == '{' ||
1254
*cp == ';' || *cp == '&' || *cp == '|');
1260
if (strcmp(cp, "cd") == 0 || strcmp(cp, "chdir") == 0) {
1261
#ifdef check_cwd_debug
1262
fprintf(stderr, " == cd, done.\n");
1266
for (mp = make; *mp != NULL; ++mp) {
1268
if (strcmp(cp, *mp) == 0) {
1269
#ifdef check_cwd_debug
1270
fprintf(stderr, " %s == '%s', chdir(%s)\n",
1277
#ifdef check_cwd_debug
1278
fprintf(stderr, "\n");
1285
Check_Cwd_Cmd(const char *cmd)
1295
av = brk_string(cmd, &ac, TRUE, &bp);
1296
#ifdef check_cwd_debug
1297
fprintf(stderr, "splitting: '%s' -> %d words\n",
1305
cp = Check_Cwd_av(ac, av, 1);
1314
Check_Cwd(const char **argv)
1322
for (ac = 0; argv[ac] != NULL; ++ac)
1324
if (ac == 3 && *argv[1] == '-') {
1325
cp = Check_Cwd_Cmd(argv[2]);
1327
cp = Check_Cwd_av(ac, UNCONST(argv), 0);
1336
* Execute the command in cmd, and return the output of that command
1340
* A string containing the output of the command, or the empty string
1341
* If err is not NULL, it contains the reason for the command failure
1344
* The string must be freed by the caller.
1347
Cmd_Exec(const char *cmd, const char **err)
1349
const char *args[4]; /* Args for invoking the shell */
1350
int fds[2]; /* Pipe streams */
1351
int cpid; /* Child PID */
1352
int pid; /* PID from wait() */
1353
char *res; /* result */
1354
int status; /* command exit status */
1355
Buffer buf; /* buffer to store the result */
1365
* Set up arguments for shell
1367
args[0] = shellName;
1373
* Open a pipe for fetching its output
1375
if (pipe(fds) == -1) {
1376
*err = "Couldn't create pipe for \"%s\"";
1383
switch (cpid = vfork()) {
1386
* Close input side of pipe
1388
(void) close(fds[0]);
1391
* Duplicate the output stream to the shell's output, then
1392
* shut the extra thing down. Note we don't fetch the error
1393
* stream...why not? Why?
1395
(void) dup2(fds[1], 1);
1396
(void) close(fds[1]);
1398
(void) execv(shellPath, UNCONST(args));
1403
*err = "Couldn't exec \"%s\"";
1408
* No need for the writing half
1410
(void) close(fds[1]);
1412
buf = Buf_Init(MAKE_BSIZE);
1415
char result[BUFSIZ];
1416
cc = read(fds[0], result, sizeof(result));
1418
Buf_AddBytes(buf, cc, (Byte *) result);
1420
while (cc > 0 || (cc == -1 && errno == EINTR));
1423
* Close the input side of the pipe.
1425
(void) close(fds[0]);
1428
* Wait for the process to exit.
1430
while(((pid = wait(&status)) != cpid) && (pid >= 0))
1433
res = (char *)Buf_GetAll (buf, &cc);
1434
Buf_Destroy(buf, FALSE);
1437
*err = "Couldn't read shell's output for \"%s\"";
1440
*err = "\"%s\" returned non-zero status";
1443
* Null-terminate the result, convert newlines to spaces and
1444
* install it in the variable.
1449
if (cc > 0 && *--cp == '\n') {
1451
* A final newline is just stripped
1472
* Print an error message given its format.
1478
* The message is printed.
1482
Error(const char *fmt, ...)
1487
fprintf(stderr, "%s: ", progname);
1488
(void)vfprintf(stderr, fmt, ap);
1490
(void)fprintf(stderr, "\n");
1491
(void)fflush(stderr);
1496
* Produce a Fatal error message. If jobs are running, waits for them
1507
Fatal(const char *fmt, ...)
1516
(void)vfprintf(stderr, fmt, ap);
1518
(void)fprintf(stderr, "\n");
1519
(void)fflush(stderr);
1523
if (DEBUG(GRAPH2) || DEBUG(GRAPH3))
1525
Trace_Log(MAKEERROR, 0);
1526
exit(2); /* Not 1 so -q can distinguish error */
1531
* Major exception once jobs are being created. Kills all jobs, prints
1532
* a message and exits.
1538
* All children are killed indiscriminately and the program Lib_Exits
1542
Punt(const char *fmt, ...)
1547
(void)fprintf(stderr, "%s: ", progname);
1548
(void)vfprintf(stderr, fmt, ap);
1550
(void)fprintf(stderr, "\n");
1551
(void)fflush(stderr);
1560
* Exit without giving a message.
1575
Trace_Log(MAKEERROR, 0);
1576
exit(2); /* Not 1, so -q can distinguish error */
1581
* Called when aborting due to errors in child shell to signal
1592
/* number of errors encountered in Make_Make */
1594
Fatal("%d error%s", errors, errors == 1 ? "" : "s");
1599
* malloc, but die on error.
1606
if ((p = malloc(len)) == NULL)
1613
* strdup, but die on error.
1616
estrdup(const char *str)
1620
if ((p = strdup(str)) == NULL)
1627
* realloc, but die on error.
1630
erealloc(void *ptr, size_t size)
1632
if ((ptr = realloc(ptr, size)) == NULL)
1639
* die when out of memory.
1644
(void)fprintf(stderr, "%s: %s.\n", progname, strerror(errno));
1650
* Remove a file carefully, avoiding directories.
1653
eunlink(const char *file)
1657
if (lstat(file, &st) == -1)
1660
if (S_ISDIR(st.st_mode)) {
1664
return unlink(file);
1669
* Print why exec failed, avoiding stdio.
1672
execError(const char *af, const char *av)
1676
struct iovec iov[8];
1678
(void)(iov[i].iov_base = UNCONST(s), \
1679
iov[i].iov_len = strlen(iov[i].iov_base), \
1682
#define IOADD (void)write(2, s, strlen(s))
1690
IOADD(") failed (");
1691
IOADD(strerror(errno));
1695
(void)writev(2, iov, 8);
1701
* exit with usage message
1706
(void)fprintf(stderr,
1707
"usage: %s [-BeikNnqrstWX] [-D variable] [-d flags] [-f makefile]\n\
1708
[-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1709
[-V variable] [variable=value] [target ...]\n", progname);
1715
PrintAddr(ClientData a, ClientData b)
1717
printf("%lx ", (unsigned long) a);
1724
PrintOnError(const char *s)
1731
printf("\n%s: stopped in %s\n", progname, curdir);
1732
strncpy(tmp, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1734
s = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
1740
Main_ExportMAKEFLAGS(Boolean first)
1742
static int once = 1;
1750
strncpy(tmp, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1752
s = Var_Subst(NULL, tmp, VAR_CMD, 0);
1755
setenv("MAKEFLAGS", s, 1);
1757
setenv("MAKE", s, 1);