1 /* $NetBSD: main.c,v 1.198 2011/09/16 15:38:04 joerg 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.198 2011/09/16 15:38:04 joerg 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.198 2011/09/16 15:38:04 joerg 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) __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
;
190 Boolean forceJobs
= FALSE
;
192 extern Lst parseIncPath
;
195 parse_debug_options(const char *argvalue
)
202 for (modules
= argvalue
; *modules
; ++modules
) {
220 debug
|= DEBUG_ERROR
;
226 if (modules
[1] == '1') {
227 debug
|= DEBUG_GRAPH1
;
230 else if (modules
[1] == '2') {
231 debug
|= DEBUG_GRAPH2
;
234 else if (modules
[1] == '3') {
235 debug
|= DEBUG_GRAPH3
;
252 debug
|= DEBUG_SCRIPT
;
255 debug
|= DEBUG_PARSE
;
267 debug
|= DEBUG_SHELL
;
270 if (debug_file
!= stdout
&& debug_file
!= stderr
)
272 if (*++modules
== '+')
276 if (strcmp(modules
, "stdout") == 0) {
280 if (strcmp(modules
, "stderr") == 0) {
284 len
= strlen(modules
);
285 fname
= malloc(len
+ 20);
286 memcpy(fname
, modules
, len
+ 1);
287 /* Let the filename be modified by the pid */
288 if (strcmp(fname
+ len
- 3, ".%d") == 0)
289 snprintf(fname
+ len
- 2, 20, "%d", getpid());
290 debug_file
= fopen(fname
, mode
);
292 fprintf(stderr
, "Cannot open debug file %s\n",
299 (void)fprintf(stderr
,
300 "%s: illegal argument to d option -- %c\n",
307 * Make the debug_file unbuffered, and make
308 * stdout line buffered (unless debugfile == stdout).
310 setvbuf(debug_file
, NULL
, _IONBF
, 0);
311 if (debug_file
!= stdout
) {
312 setvbuf(stdout
, NULL
, _IOLBF
, 0);
318 * Parse a given argument vector. Called from main() and from
319 * Main_ParseArgLine() when the .MAKEFLAGS target is used.
321 * XXX: Deal with command line overriding .MAKEFLAGS in makefile
327 * Various global and local flags will be set depending on the flags
331 MainParseArgs(int argc
, char **argv
)
337 const char *getopt_def
;
339 Boolean inOption
, dashDash
= FALSE
;
340 char found_path
[MAXPATHLEN
+ 1]; /* for searching for sys.mk */
342 #define OPTFLAGS "BC:D:I:J:NST:V:WXd:ef:ij:km:nqrst"
343 /* Can't actually use getopt(3) because rescanning is not portable */
345 getopt_def
= OPTFLAGS
;
363 if (c
!= '-' || dashDash
)
368 /* '-' found at some earlier point */
369 getopt_spec
= strchr(getopt_def
, c
);
370 if(c
!= '\0' && getopt_spec
!= NULL
&& getopt_spec
[1] == ':') {
371 /* -<something> found, and <something> should have an arg */
375 if(*argvalue
== '\0') {
391 Var_Append(MAKEFLAGS
, "-B", VAR_GLOBAL
);
392 Var_Set(MAKE_MODE
, "compat", VAR_GLOBAL
, 0);
395 if (chdir(argvalue
) == -1) {
396 (void)fprintf(stderr
,
397 "%s: chdir %s: %s\n",
402 if (getcwd(curdir
, MAXPATHLEN
) == NULL
) {
403 (void)fprintf(stderr
, "%s: %s.\n", progname
, strerror(errno
));
409 if (argvalue
== NULL
|| argvalue
[0] == 0) goto noarg
;
410 Var_Set(argvalue
, "1", VAR_GLOBAL
, 0);
411 Var_Append(MAKEFLAGS
, "-D", VAR_GLOBAL
);
412 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
415 if (argvalue
== NULL
) goto noarg
;
416 Parse_AddIncludeDir(argvalue
);
417 Var_Append(MAKEFLAGS
, "-I", VAR_GLOBAL
);
418 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
421 if (argvalue
== NULL
) goto noarg
;
422 if (sscanf(argvalue
, "%d,%d", &jp_0
, &jp_1
) != 2) {
423 (void)fprintf(stderr
,
424 "%s: internal error -- J option malformed (%s)\n",
428 if ((fcntl(jp_0
, F_GETFD
, 0) < 0) ||
429 (fcntl(jp_1
, F_GETFD
, 0) < 0)) {
431 (void)fprintf(stderr
,
432 "%s: ###### warning -- J descriptors were closed!\n",
440 Var_Append(MAKEFLAGS
, "-J", VAR_GLOBAL
);
441 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
447 noRecursiveExecute
= TRUE
;
448 Var_Append(MAKEFLAGS
, "-N", VAR_GLOBAL
);
452 Var_Append(MAKEFLAGS
, "-S", VAR_GLOBAL
);
455 if (argvalue
== NULL
) goto noarg
;
456 tracefile
= bmake_strdup(argvalue
);
457 Var_Append(MAKEFLAGS
, "-T", VAR_GLOBAL
);
458 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
461 if (argvalue
== NULL
) goto noarg
;
463 (void)Lst_AtEnd(variables
, argvalue
);
464 Var_Append(MAKEFLAGS
, "-V", VAR_GLOBAL
);
465 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
468 parseWarnFatal
= TRUE
;
471 varNoExportEnv
= TRUE
;
472 Var_Append(MAKEFLAGS
, "-X", VAR_GLOBAL
);
475 if (argvalue
== NULL
) goto noarg
;
476 /* If '-d-opts' don't pass to children */
477 if (argvalue
[0] == '-')
480 Var_Append(MAKEFLAGS
, "-d", VAR_GLOBAL
);
481 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
483 parse_debug_options(argvalue
);
486 checkEnvFirst
= TRUE
;
487 Var_Append(MAKEFLAGS
, "-e", VAR_GLOBAL
);
490 if (argvalue
== NULL
) goto noarg
;
491 (void)Lst_AtEnd(makefiles
, argvalue
);
495 Var_Append(MAKEFLAGS
, "-i", VAR_GLOBAL
);
498 if (argvalue
== NULL
) goto noarg
;
500 maxJobs
= strtol(argvalue
, &p
, 0);
501 if (*p
!= '\0' || maxJobs
< 1) {
502 (void)fprintf(stderr
, "%s: illegal argument to -j -- must be positive integer!\n",
506 Var_Append(MAKEFLAGS
, "-j", VAR_GLOBAL
);
507 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
508 Var_Set(".MAKE.JOBS", argvalue
, VAR_GLOBAL
, 0);
509 maxJobTokens
= maxJobs
;
513 Var_Append(MAKEFLAGS
, "-k", VAR_GLOBAL
);
516 if (argvalue
== NULL
) goto noarg
;
517 /* look for magic parent directory search string */
518 if (strncmp(".../", argvalue
, 4) == 0) {
519 if (!Dir_FindHereOrAbove(curdir
, argvalue
+4,
520 found_path
, sizeof(found_path
)))
521 break; /* nothing doing */
522 (void)Dir_AddDir(sysIncPath
, found_path
);
524 (void)Dir_AddDir(sysIncPath
, argvalue
);
526 Var_Append(MAKEFLAGS
, "-m", VAR_GLOBAL
);
527 Var_Append(MAKEFLAGS
, argvalue
, VAR_GLOBAL
);
531 Var_Append(MAKEFLAGS
, "-n", VAR_GLOBAL
);
535 /* Kind of nonsensical, wot? */
536 Var_Append(MAKEFLAGS
, "-q", VAR_GLOBAL
);
540 Var_Append(MAKEFLAGS
, "-r", VAR_GLOBAL
);
544 Var_Append(MAKEFLAGS
, "-s", VAR_GLOBAL
);
548 Var_Append(MAKEFLAGS
, "-t", VAR_GLOBAL
);
564 * See if the rest of the arguments are variable assignments and
565 * perform them if so. Else take them to be targets and stuff them
566 * on the end of the "create" list.
568 for (; argc
> 1; ++argv
, --argc
)
569 if (Parse_IsVar(argv
[1])) {
570 Parse_DoVar(argv
[1], VAR_CMD
);
573 Punt("illegal (null) argument.");
574 if (*argv
[1] == '-' && !dashDash
)
576 (void)Lst_AtEnd(create
, bmake_strdup(argv
[1]));
581 (void)fprintf(stderr
, "%s: option requires an argument -- %c\n",
587 * Main_ParseArgLine --
588 * Used by the parse module when a .MFLAGS or .MAKEFLAGS target
589 * is encountered and by main() when reading the .MAKEFLAGS envariable.
590 * Takes a line of arguments and breaks it into its
591 * component words and passes those words and the number of them to the
592 * MainParseArgs function.
593 * The line should have all its leading whitespace removed.
596 * line Line to fracture
602 * Only those that come from the various arguments.
605 Main_ParseArgLine(const char *line
)
607 char **argv
; /* Manufactured argument vector */
608 int argc
; /* Number of arguments in argv */
609 char *args
; /* Space used by the args */
611 char *argv0
= Var_Value(".MAKE", VAR_GLOBAL
, &p1
);
616 for (; *line
== ' '; ++line
)
621 buf
= bmake_malloc(len
= strlen(line
) + strlen(argv0
) + 2);
622 (void)snprintf(buf
, len
, "%s %s", argv0
, line
);
626 argv
= brk_string(buf
, &argc
, TRUE
, &args
);
628 Error("Unterminated quoted string [%s]", buf
);
633 MainParseArgs(argc
, argv
);
640 Main_SetObjdir(const char *path
)
644 char buf
[MAXPATHLEN
+ 1];
647 /* expand variable substitutions */
648 if (strchr(path
, '$') != 0) {
649 snprintf(buf
, MAXPATHLEN
, "%s", path
);
650 path
= p
= Var_Subst(NULL
, buf
, VAR_GLOBAL
, 0);
653 if (path
[0] != '/') {
654 snprintf(buf
, MAXPATHLEN
, "%s/%s", curdir
, path
);
658 /* look for the directory and try to chdir there */
659 if (stat(path
, &sb
) == 0 && S_ISDIR(sb
.st_mode
)) {
661 (void)fprintf(stderr
, "make warning: %s: %s.\n",
662 path
, strerror(errno
));
664 strncpy(objdir
, path
, MAXPATHLEN
);
665 Var_Set(".OBJDIR", objdir
, VAR_GLOBAL
, 0);
666 setenv("PWD", objdir
, 1);
678 * ReadAllMakefiles --
679 * wrapper around ReadMakefile() to read all.
682 * TRUE if ok, FALSE on error
685 ReadAllMakefiles(const void *p
, const void *q
)
687 return (ReadMakefile(p
, q
) == 0);
691 str2Lst_Append(Lst lp
, char *str
, const char *sep
)
699 for (n
= 0, cp
= strtok(str
, sep
); cp
; cp
= strtok(NULL
, sep
)) {
700 (void)Lst_AtEnd(lp
, cp
);
709 siginfo(int signo __unused
)
711 char dir
[MAXPATHLEN
];
712 char str
[2 * MAXPATHLEN
];
714 if (getcwd(dir
, sizeof(dir
)) == NULL
)
716 len
= snprintf(str
, sizeof(str
), "%s: Working in: %s\n", progname
, dir
);
718 (void)write(STDERR_FILENO
, str
, (size_t)len
);
723 * Allow makefiles some control over the mode we run in.
726 MakeMode(const char *mode
)
731 mode
= mp
= Var_Subst(NULL
, "${" MAKE_MODE
":tl}", VAR_GLOBAL
, 0);
734 if (strstr(mode
, "compat")) {
739 if (strstr(mode
, "meta"))
749 * The main function, for obvious reasons. Initializes variables
750 * and a few modules, then parses the arguments give it in the
751 * environment and on the command line. Reads the system makefile
752 * followed by either Makefile, makefile or the file given by the
753 * -f argument. Sets the .MAKEFLAGS PMake variable based on all the
754 * flags it has received by then uses either the Make or the Compat
755 * module to create the initial list of targets.
758 * If -q was given, exits -1 if anything was out-of-date. Else it exits
762 * The program exits when done. Targets are created. etc. etc. etc.
765 main(int argc
, char **argv
)
767 Lst targs
; /* target nodes to create -- passed to Make_Init */
768 Boolean outOfDate
= FALSE
; /* FALSE if all targets up to date */
770 char *p1
, *path
, *pwd
;
771 char mdpath
[MAXPATHLEN
];
772 const char *machine
= getenv("MACHINE");
773 const char *machine_arch
= getenv("MACHINE_ARCH");
774 char *syspath
= getenv("MAKESYSPATH");
775 Lst sysMkPath
; /* Path of sys.mk */
776 char *cp
= NULL
, *start
;
777 /* avoid faults on read-only strings */
778 static char defsyspath
[] = _PATH_DEFSYSPATH
;
779 char found_path
[MAXPATHLEN
+ 1]; /* for searching for sys.mk */
780 struct timeval rightnow
; /* to initialize random seed */
782 struct utsname utsname
;
785 /* default to writing debug to stderr */
789 (void)bmake_signal(SIGINFO
, siginfo
);
792 * Set the seed to produce a different random sequence
793 * on each program execution.
795 gettimeofday(&rightnow
, NULL
);
796 srandom(rightnow
.tv_sec
+ rightnow
.tv_usec
);
798 if ((progname
= strrchr(argv
[0], '/')) != NULL
)
802 #if defined(RLIMIT_NOFILE) && !defined(__minix)
804 * get rid of resource limit on file descriptors
808 if (getrlimit(RLIMIT_NOFILE
, &rl
) != -1 &&
809 rl
.rlim_cur
!= rl
.rlim_max
) {
810 rl
.rlim_cur
= rl
.rlim_max
;
811 (void)setrlimit(RLIMIT_NOFILE
, &rl
);
817 * Get the name of this type of MACHINE from utsname
818 * so we can share an executable for similar machines.
819 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
821 * Note that both MACHINE and MACHINE_ARCH are decided at
826 if (uname(&utsname
) == -1) {
827 (void)fprintf(stderr
, "%s: uname failed (%s).\n", progname
,
831 machine
= utsname
.machine
;
834 machine
= MAKE_MACHINE
;
843 #ifdef MAKE_MACHINE_ARCH
844 machine_arch
= MAKE_MACHINE_ARCH
;
846 machine_arch
= "unknown";
849 machine_arch
= MACHINE_ARCH
;
853 myPid
= getpid(); /* remember this for vFork() */
856 * Just in case MAKEOBJDIR wants us to do something tricky.
858 Var_Init(); /* Initialize the lists of variables for
859 * parsing arguments */
860 Var_Set("MACHINE", machine
, VAR_GLOBAL
, 0);
861 Var_Set("MACHINE_ARCH", machine_arch
, VAR_GLOBAL
, 0);
863 Var_Set("MAKE_VERSION", MAKE_VERSION
, VAR_GLOBAL
, 0);
865 Var_Set(".newline", "\n", VAR_GLOBAL
, 0); /* handy for :@ loops */
867 * This is the traditional preference for makefiles.
869 #ifndef MAKEFILE_PREFERENCE_LIST
870 # define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
872 Var_Set(MAKEFILE_PREFERENCE
, MAKEFILE_PREFERENCE_LIST
,
874 Var_Set(MAKE_DEPENDFILE
, ".depend", VAR_GLOBAL
, 0);
876 create
= Lst_Init(FALSE
);
877 makefiles
= Lst_Init(FALSE
);
879 variables
= Lst_Init(FALSE
);
880 beSilent
= FALSE
; /* Print commands as executed */
881 ignoreErrors
= FALSE
; /* Pay attention to non-zero returns */
882 noExecute
= FALSE
; /* Execute all commands */
883 noRecursiveExecute
= FALSE
; /* Execute all .MAKE targets */
884 keepgoing
= FALSE
; /* Stop on error */
885 allPrecious
= FALSE
; /* Remove targets when interrupted */
886 queryFlag
= FALSE
; /* This is not just a check-run */
887 noBuiltins
= FALSE
; /* Read the built-in rules */
888 touchFlag
= FALSE
; /* Actually update targets */
889 debug
= 0; /* No debug verbosity, please. */
892 maxJobs
= DEFMAXLOCAL
; /* Set default local max concurrency */
893 maxJobTokens
= maxJobs
;
894 compatMake
= FALSE
; /* No compat mode */
898 * Initialize the parsing, directory and variable modules to prepare
899 * for the reading of inclusion paths and variable settings on the
904 * Initialize various variables.
905 * MAKE also gets this name, for compatibility
906 * .MAKEFLAGS gets set to the empty string just in case.
907 * MFLAGS also gets initialized empty, for compatibility.
910 if (argv
[0][0] == '/' || strchr(argv
[0], '/') == NULL
) {
912 * Leave alone if it is an absolute path, or if it does
913 * not contain a '/' in which case we need to find it in
914 * the path, like execvp(3) and the shells do.
919 * A relative path, canonicalize it.
921 p1
= realpath(argv
[0], mdpath
);
922 if (!p1
|| *p1
!= '/' || stat(p1
, &sb
) < 0) {
923 p1
= argv
[0]; /* realpath failed */
926 Var_Set("MAKE", p1
, VAR_GLOBAL
, 0);
927 Var_Set(".MAKE", p1
, VAR_GLOBAL
, 0);
928 Var_Set(MAKEFLAGS
, "", VAR_GLOBAL
, 0);
929 Var_Set(MAKEOVERRIDES
, "", VAR_GLOBAL
, 0);
930 Var_Set("MFLAGS", "", VAR_GLOBAL
, 0);
931 Var_Set(".ALLTARGETS", "", VAR_GLOBAL
, 0);
934 * Set some other useful macros
940 if (!(ep
= getenv(MAKE_LEVEL
))) {
943 Var_Set(MAKE_LEVEL
, ep
, VAR_GLOBAL
, 0);
944 snprintf(tmp
, sizeof(tmp
), "%u", myPid
);
945 Var_Set(".MAKE.PID", tmp
, VAR_GLOBAL
, 0);
946 snprintf(tmp
, sizeof(tmp
), "%u", getppid());
947 Var_Set(".MAKE.PPID", tmp
, VAR_GLOBAL
, 0);
952 * First snag any flags out of the MAKE environment variable.
953 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
954 * in a different format).
957 Main_ParseArgLine(getenv("MAKEFLAGS"));
959 Main_ParseArgLine(getenv("MAKE"));
963 * Find where we are (now).
964 * We take care of PWD for the automounter below...
966 if (getcwd(curdir
, MAXPATHLEN
) == NULL
) {
967 (void)fprintf(stderr
, "%s: getcwd: %s.\n",
968 progname
, strerror(errno
));
972 MainParseArgs(argc
, argv
);
975 * Verify that cwd is sane.
977 if (stat(curdir
, &sa
) == -1) {
978 (void)fprintf(stderr
, "%s: %s: %s.\n",
979 progname
, curdir
, strerror(errno
));
984 * All this code is so that we know where we are when we start up
985 * on a different machine with pmake.
986 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
987 * since the value of curdir can vary depending on how we got
988 * here. Ie sitting at a shell prompt (shell that provides $PWD)
989 * or via subdir.mk in which case its likely a shell which does
991 * So, to stop it breaking this case only, we ignore PWD if
992 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
995 (pwd
= getenv("PWD")) != NULL
&&
996 getenv("MAKEOBJDIRPREFIX") == NULL
) {
997 const char *makeobjdir
= getenv("MAKEOBJDIR");
999 if (makeobjdir
== NULL
|| !strchr(makeobjdir
, '$')) {
1000 if (stat(pwd
, &sb
) == 0 && sa
.st_ino
== sb
.st_ino
&&
1001 sa
.st_dev
== sb
.st_dev
)
1002 (void)strncpy(curdir
, pwd
, MAXPATHLEN
);
1005 Var_Set(".CURDIR", curdir
, VAR_GLOBAL
, 0);
1008 * Find the .OBJDIR. If MAKEOBJDIRPREFIX, or failing that,
1009 * MAKEOBJDIR is set in the environment, try only that value
1010 * and fall back to .CURDIR if it does not exist.
1012 * Otherwise, try _PATH_OBJDIR.MACHINE, _PATH_OBJDIR, and
1013 * finally _PATH_OBJDIRPREFIX`pwd`, in that order. If none
1014 * of these paths exist, just use .CURDIR.
1017 (void)Main_SetObjdir(curdir
);
1019 if ((path
= getenv("MAKEOBJDIRPREFIX")) != NULL
) {
1020 (void)snprintf(mdpath
, MAXPATHLEN
, "%s%s", path
, curdir
);
1021 (void)Main_SetObjdir(mdpath
);
1022 } else if ((path
= getenv("MAKEOBJDIR")) != NULL
) {
1023 (void)Main_SetObjdir(path
);
1025 (void)snprintf(mdpath
, MAXPATHLEN
, "%s.%s", _PATH_OBJDIR
, machine
);
1026 if (!Main_SetObjdir(mdpath
) && !Main_SetObjdir(_PATH_OBJDIR
)) {
1027 (void)snprintf(mdpath
, MAXPATHLEN
, "%s%s",
1028 _PATH_OBJDIRPREFIX
, curdir
);
1029 (void)Main_SetObjdir(mdpath
);
1034 * Be compatible if user did not specify -j and did not explicitly
1035 * turned compatibility on
1037 if (!compatMake
&& !forceJobs
) {
1042 * Initialize archive, target and suffix modules in preparation for
1043 * parsing the makefile(s)
1048 Trace_Init(tracefile
);
1053 Trace_Log(MAKESTART
, NULL
);
1056 * Set up the .TARGETS variable to contain the list of targets to be
1057 * created. If none specified, make the variable empty -- the parser
1058 * will fill the thing in with the default or .MAIN target.
1060 if (!Lst_IsEmpty(create
)) {
1063 for (ln
= Lst_First(create
); ln
!= NULL
;
1064 ln
= Lst_Succ(ln
)) {
1065 char *name
= (char *)Lst_Datum(ln
);
1067 Var_Append(".TARGETS", name
, VAR_GLOBAL
);
1070 Var_Set(".TARGETS", "", VAR_GLOBAL
, 0);
1074 * If no user-supplied system path was given (through the -m option)
1075 * add the directories from the DEFSYSPATH (more than one may be given
1076 * as dir1:...:dirn) to the system include path.
1078 if (syspath
== NULL
|| *syspath
== '\0')
1079 syspath
= defsyspath
;
1081 syspath
= bmake_strdup(syspath
);
1083 for (start
= syspath
; *start
!= '\0'; start
= cp
) {
1084 for (cp
= start
; *cp
!= '\0' && *cp
!= ':'; cp
++)
1089 /* look for magic parent directory search string */
1090 if (strncmp(".../", start
, 4) != 0) {
1091 (void)Dir_AddDir(defIncPath
, start
);
1093 if (Dir_FindHereOrAbove(curdir
, start
+4,
1094 found_path
, sizeof(found_path
))) {
1095 (void)Dir_AddDir(defIncPath
, found_path
);
1099 if (syspath
!= defsyspath
)
1103 * Read in the built-in rules first, followed by the specified
1104 * makefile, if it was (makefile != NULL), or the default
1105 * makefile and Makefile, in that order, if it wasn't.
1110 sysMkPath
= Lst_Init(FALSE
);
1111 Dir_Expand(_PATH_DEFSYSMK
,
1112 Lst_IsEmpty(sysIncPath
) ? defIncPath
: sysIncPath
,
1114 if (Lst_IsEmpty(sysMkPath
))
1115 Fatal("%s: no system rules (%s).", progname
,
1117 ln
= Lst_Find(sysMkPath
, NULL
, ReadMakefile
);
1119 Fatal("%s: cannot open %s.", progname
,
1120 (char *)Lst_Datum(ln
));
1123 if (!Lst_IsEmpty(makefiles
)) {
1126 ln
= Lst_Find(makefiles
, NULL
, ReadAllMakefiles
);
1128 Fatal("%s: cannot open %s.", progname
,
1129 (char *)Lst_Datum(ln
));
1131 p1
= Var_Subst(NULL
, "${" MAKEFILE_PREFERENCE
"}",
1134 (void)str2Lst_Append(makefiles
, p1
, NULL
);
1135 (void)Lst_Find(makefiles
, NULL
, ReadMakefile
);
1140 /* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
1141 if (!noBuiltins
|| !printVars
) {
1142 makeDependfile
= Var_Subst(NULL
, "${.MAKE.DEPENDFILE:T}",
1144 doing_depend
= TRUE
;
1145 (void)ReadMakefile(makeDependfile
, NULL
);
1146 doing_depend
= FALSE
;
1151 Var_Append("MFLAGS", Var_Value(MAKEFLAGS
, VAR_GLOBAL
, &p1
), VAR_GLOBAL
);
1156 Job_ServerStart(maxJobTokens
, jp_0
, jp_1
);
1158 fprintf(debug_file
, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
1159 jp_0
, jp_1
, maxJobs
, maxJobTokens
, compatMake
);
1161 Main_ExportMAKEFLAGS(TRUE
); /* initial export */
1163 Check_Cwd_av(0, NULL
, 0); /* initialize it */
1167 * For compatibility, look at the directories in the VPATH variable
1168 * and add them to the search path, if the variable is defined. The
1169 * variable's value is in the same format as the PATH envariable, i.e.
1170 * <directory>:<directory>:<directory>...
1172 if (Var_Exists("VPATH", VAR_CMD
)) {
1175 * GCC stores string constants in read-only memory, but
1176 * Var_Subst will want to write this thing, so store it
1179 static char VPATH
[] = "${VPATH}";
1181 vpath
= Var_Subst(NULL
, VPATH
, VAR_CMD
, FALSE
);
1184 /* skip to end of directory */
1185 for (cp
= path
; *cp
!= ':' && *cp
!= '\0'; cp
++)
1187 /* Save terminator character so know when to stop */
1190 /* Add directory to search path */
1191 (void)Dir_AddDir(dirSearchPath
, path
);
1194 } while (savec
== ':');
1199 * Now that all search paths have been read for suffixes et al, it's
1200 * time to add the default search path to their lists...
1205 * Propagate attributes through :: dependency lists.
1209 /* print the initial graph, if the user requested it */
1213 /* print the values of any variables requested by the user */
1217 for (ln
= Lst_First(variables
); ln
!= NULL
;
1218 ln
= Lst_Succ(ln
)) {
1219 char *var
= (char *)Lst_Datum(ln
);
1222 if (strchr(var
, '$')) {
1223 value
= p1
= Var_Subst(NULL
, var
, VAR_GLOBAL
, 0);
1225 value
= Var_Value(var
, VAR_GLOBAL
, &p1
);
1227 printf("%s\n", value
? value
: "");
1233 * Have now read the entire graph and need to make a list of
1234 * targets to create. If none was given on the command line,
1235 * we consult the parsing module to find the main target(s)
1238 if (Lst_IsEmpty(create
))
1239 targs
= Parse_MainName();
1241 targs
= Targ_FindList(create
, TARG_CREATE
);
1245 * Initialize job module before traversing the graph
1246 * now that any .BEGIN and .END targets have been read.
1247 * This is done only if the -q flag wasn't given
1248 * (to prevent the .BEGIN from being executed should
1256 /* Traverse the graph, checking on all the targets */
1257 outOfDate
= Make_Run(targs
);
1260 * Compat_Init will take care of creating all the
1261 * targets as well as initializing the module.
1268 Lst_Destroy(targs
, NULL
);
1269 Lst_Destroy(variables
, NULL
);
1270 Lst_Destroy(makefiles
, NULL
);
1271 Lst_Destroy(create
, (FreeProc
*)free
);
1274 /* print the graph now it's been processed if the user requested it */
1278 Trace_Log(MAKEEND
, 0);
1289 return outOfDate
? 1 : 0;
1294 * Open and parse the given makefile.
1297 * 0 if ok. -1 if couldn't open file.
1303 ReadMakefile(const void *p
, const void *q __unused
)
1305 const char *fname
= p
; /* makefile to read */
1307 size_t len
= MAXPATHLEN
;
1308 char *name
, *path
= bmake_malloc(len
);
1310 if (!strcmp(fname
, "-")) {
1311 Parse_File(NULL
/*stdin*/, -1);
1312 Var_Set("MAKEFILE", "", VAR_GLOBAL
, 0);
1314 /* if we've chdir'd, rebuild the path name */
1315 if (strcmp(curdir
, objdir
) && *fname
!= '/') {
1316 size_t plen
= strlen(curdir
) + strlen(fname
) + 2;
1318 path
= bmake_realloc(path
, len
= 2 * plen
);
1320 (void)snprintf(path
, len
, "%s/%s", curdir
, fname
);
1321 fd
= open(path
, O_RDONLY
);
1327 /* If curdir failed, try objdir (ala .depend) */
1328 plen
= strlen(objdir
) + strlen(fname
) + 2;
1330 path
= bmake_realloc(path
, len
= 2 * plen
);
1331 (void)snprintf(path
, len
, "%s/%s", objdir
, fname
);
1332 fd
= open(path
, O_RDONLY
);
1338 fd
= open(fname
, O_RDONLY
);
1342 /* look in -I and system include directories. */
1343 name
= Dir_FindFile(fname
, parseIncPath
);
1345 name
= Dir_FindFile(fname
,
1346 Lst_IsEmpty(sysIncPath
) ? defIncPath
: sysIncPath
);
1347 if (!name
|| (fd
= open(name
, O_RDONLY
)) == -1) {
1355 * set the MAKEFILE variable desired by System V fans -- the
1356 * placement of the setting here means it gets set to the last
1357 * makefile specified, as it is set by SysV make.
1361 Var_Set("MAKEFILE", fname
, VAR_GLOBAL
, 0);
1362 Parse_File(fname
, fd
);
1370 * If MAKEOBJDIRPREFIX is in use, make ends up not in .CURDIR
1371 * in situations that would not arrise with ./obj (links or not).
1372 * This tends to break things like:
1377 * This function spots when ${.MAKE:T} or ${.MAKE} is a command (as
1378 * opposed to an argument) in a command line and if so returns
1379 * ${.CURDIR} so caller can chdir() so that the assumptions made by
1380 * the Makefile hold true.
1382 * If ${.MAKE} does not contain any '/', then ${.MAKE:T} is skipped.
1384 * The chdir() only happens in the child process, and does nothing if
1385 * MAKEOBJDIRPREFIX and MAKEOBJDIR are not in the environment so it
1386 * should not break anything. Also if NOCHECKMAKECHDIR is set we
1387 * do nothing - to ensure historic semantics can be retained.
1389 static int Check_Cwd_Off
= 0;
1392 Check_Cwd_av(int ac
, char **av
, int copy
)
1394 static char *make
[4];
1395 static char *cur_dir
= NULL
;
1398 int is_cmd
, next_cmd
;
1402 if (Check_Cwd_Off
) {
1404 fprintf(debug_file
, "check_cwd: check is off.\n");
1408 if (make
[0] == NULL
) {
1409 if (Var_Exists("NOCHECKMAKECHDIR", VAR_GLOBAL
)) {
1412 fprintf(debug_file
, "check_cwd: turning check off.\n");
1416 make
[1] = Var_Value(".MAKE", VAR_GLOBAL
, &cp
);
1417 if ((make
[0] = strrchr(make
[1], '/')) == NULL
) {
1423 cur_dir
= Var_Value(".CURDIR", VAR_GLOBAL
, &cp
);
1425 if (ac
== 0 || av
== NULL
) {
1427 fprintf(debug_file
, "check_cwd: empty command.\n");
1428 return NULL
; /* initialization only */
1431 if (getenv("MAKEOBJDIR") == NULL
&&
1432 getenv("MAKEOBJDIRPREFIX") == NULL
) {
1434 fprintf(debug_file
, "check_cwd: no obj dirs.\n");
1440 for (i
= 0; i
< ac
; ++i
) {
1444 cp
= &(av
[i
])[n
- 1];
1445 if (strspn(av
[i
], "|&;") == (size_t)n
) {
1448 } else if (*cp
== ';' || *cp
== '&' || *cp
== '|' || *cp
== ')') {
1453 } while (*cp
== ';' || *cp
== '&' || *cp
== '|' ||
1454 *cp
== ')' || *cp
== '}') ;
1457 * XXX this should not happen.
1459 fprintf(stderr
, "%s: WARNING: raw arg ends in shell meta '%s'\n",
1466 if (*cp
== ';' || *cp
== '&' || *cp
== '|')
1470 fprintf(debug_file
, "av[%d] == %s '%s'",
1471 i
, (is_cmd
) ? "cmd" : "arg", av
[i
]);
1473 if (*cp
== '(' || *cp
== '{' ||
1474 *cp
== ';' || *cp
== '&' || *cp
== '|') {
1477 } while (*cp
== '(' || *cp
== '{' ||
1478 *cp
== ';' || *cp
== '&' || *cp
== '|');
1484 if (strcmp(cp
, "cd") == 0 || strcmp(cp
, "chdir") == 0) {
1486 fprintf(debug_file
, " == cd, done.\n");
1489 for (mp
= make
; *mp
!= NULL
; ++mp
) {
1491 if (strcmp(cp
, *mp
) == 0) {
1493 fprintf(debug_file
, " %s == '%s', chdir(%s)\n",
1500 fprintf(debug_file
, "\n");
1506 Check_Cwd_Cmd(const char *cmd
)
1516 av
= brk_string(cmd
, &ac
, TRUE
, &bp
);
1518 fprintf(debug_file
, "splitting: '%s' -> %d words\n",
1525 cp
= Check_Cwd_av(ac
, av
, 1);
1534 Check_Cwd(const char **argv
)
1542 for (ac
= 0; argv
[ac
] != NULL
; ++ac
)
1544 if (ac
== 3 && *argv
[1] == '-') {
1545 cp
= Check_Cwd_Cmd(argv
[2]);
1547 cp
= Check_Cwd_av(ac
, UNCONST(argv
), 0);
1556 * Execute the command in cmd, and return the output of that command
1560 * A string containing the output of the command, or the empty string
1561 * If errnum is not NULL, it contains the reason for the command failure
1564 * The string must be freed by the caller.
1567 Cmd_Exec(const char *cmd
, const char **errnum
)
1569 const char *args
[4]; /* Args for invoking the shell */
1570 int fds
[2]; /* Pipe streams */
1571 int cpid
; /* Child PID */
1572 int pid
; /* PID from wait() */
1573 char *res
; /* result */
1574 int status
; /* command exit status */
1575 Buffer buf
; /* buffer to store the result */
1585 * Set up arguments for shell
1587 args
[0] = shellName
;
1593 * Open a pipe for fetching its output
1595 if (pipe(fds
) == -1) {
1596 *errnum
= "Couldn't create pipe for \"%s\"";
1603 switch (cpid
= vFork()) {
1606 * Close input side of pipe
1608 (void)close(fds
[0]);
1611 * Duplicate the output stream to the shell's output, then
1612 * shut the extra thing down. Note we don't fetch the error
1613 * stream...why not? Why?
1615 (void)dup2(fds
[1], 1);
1616 (void)close(fds
[1]);
1620 (void)execv(shellPath
, UNCONST(args
));
1625 *errnum
= "Couldn't exec \"%s\"";
1630 * No need for the writing half
1632 (void)close(fds
[1]);
1637 char result
[BUFSIZ
];
1638 cc
= read(fds
[0], result
, sizeof(result
));
1640 Buf_AddBytes(&buf
, cc
, result
);
1642 while (cc
> 0 || (cc
== -1 && errno
== EINTR
));
1645 * Close the input side of the pipe.
1647 (void)close(fds
[0]);
1650 * Wait for the process to exit.
1652 while(((pid
= waitpid(cpid
, &status
, 0)) != cpid
) && (pid
>= 0)) {
1653 JobReapChild(pid
, status
, FALSE
);
1656 cc
= Buf_Size(&buf
);
1657 res
= Buf_Destroy(&buf
, FALSE
);
1660 *errnum
= "Couldn't read shell's output for \"%s\"";
1662 if (WIFSIGNALED(status
))
1663 *errnum
= "\"%s\" exited on a signal";
1664 else if (WEXITSTATUS(status
) != 0)
1665 *errnum
= "\"%s\" returned non-zero status";
1668 * Null-terminate the result, convert newlines to spaces and
1669 * install it in the variable.
1674 if (cc
> 0 && *--cp
== '\n') {
1676 * A final newline is just stripped
1690 res
= bmake_malloc(1);
1697 * Print an error message given its format.
1703 * The message is printed.
1707 Error(const char *fmt
, ...)
1712 err_file
= debug_file
;
1713 if (err_file
== stdout
)
1715 (void)fflush(stdout
);
1718 fprintf(err_file
, "%s: ", progname
);
1719 (void)vfprintf(err_file
, fmt
, ap
);
1721 (void)fprintf(err_file
, "\n");
1722 (void)fflush(err_file
);
1723 if (err_file
== stderr
)
1731 * Produce a Fatal error message. If jobs are running, waits for them
1742 Fatal(const char *fmt
, ...)
1750 (void)fflush(stdout
);
1751 (void)vfprintf(stderr
, fmt
, ap
);
1753 (void)fprintf(stderr
, "\n");
1754 (void)fflush(stderr
);
1756 PrintOnError(NULL
, NULL
);
1758 if (DEBUG(GRAPH2
) || DEBUG(GRAPH3
))
1760 Trace_Log(MAKEERROR
, 0);
1761 exit(2); /* Not 1 so -q can distinguish error */
1766 * Major exception once jobs are being created. Kills all jobs, prints
1767 * a message and exits.
1773 * All children are killed indiscriminately and the program Lib_Exits
1777 Punt(const char *fmt
, ...)
1782 (void)fflush(stdout
);
1783 (void)fprintf(stderr
, "%s: ", progname
);
1784 (void)vfprintf(stderr
, fmt
, ap
);
1786 (void)fprintf(stderr
, "\n");
1787 (void)fflush(stderr
);
1789 PrintOnError(NULL
, NULL
);
1796 * Exit without giving a message.
1811 Trace_Log(MAKEERROR
, 0);
1812 exit(2); /* Not 1, so -q can distinguish error */
1817 * Called when aborting due to errors in child shell to signal
1828 /* number of errors encountered in Make_Make */
1830 Fatal("%d error%s", errors
, errors
== 1 ? "" : "s");
1835 * Remove a file carefully, avoiding directories.
1838 eunlink(const char *file
)
1842 if (lstat(file
, &st
) == -1)
1845 if (S_ISDIR(st
.st_mode
)) {
1849 return unlink(file
);
1854 * Print why exec failed, avoiding stdio.
1857 execError(const char *af
, const char *av
)
1861 struct iovec iov
[8];
1863 (void)(iov[i].iov_base = UNCONST(s), \
1864 iov[i].iov_len = strlen(iov[i].iov_base), \
1867 #define IOADD(void)write(2, s, strlen(s))
1875 IOADD(") failed (");
1876 IOADD(strerror(errno
));
1880 (void)writev(2, iov
, 8);
1886 * exit with usage message
1891 (void)fprintf(stderr
,
1892 "usage: %s [-BeikNnqrstWX] \n\
1893 [-C directory] [-D variable] [-d flags] [-f makefile]\n\
1894 [-I directory] [-J private] [-j max_jobs] [-m directory] [-T file]\n\
1895 [-V variable] [variable=value] [target ...]\n", progname
);
1901 PrintAddr(void *a
, void *b
)
1903 printf("%lx ", (unsigned long) a
);
1910 PrintOnError(GNode
*gn
, const char *s
)
1912 static GNode
*en
= NULL
;
1919 printf("\n%s: stopped in %s\n", progname
, curdir
);
1922 return; /* we've been here! */
1925 * We can print this even if there is no .ERROR target.
1927 Var_Set(".ERROR_TARGET", gn
->name
, VAR_GLOBAL
, 0);
1929 strncpy(tmp
, "${MAKE_PRINT_VAR_ON_ERROR:@v@$v='${$v}'\n@}",
1931 cp
= Var_Subst(NULL
, tmp
, VAR_GLOBAL
, 0);
1938 * Finally, see if there is a .ERROR target, and run it if so.
1940 en
= Targ_FindNode(".ERROR", TARG_NOCREATE
);
1942 en
->type
|= OP_SPECIAL
;
1943 Compat_Make(en
, en
);
1948 Main_ExportMAKEFLAGS(Boolean first
)
1950 static int once
= 1;
1958 strncpy(tmp
, "${.MAKEFLAGS} ${.MAKEOVERRIDES:O:u:@v@$v=${$v:Q}@}",
1960 s
= Var_Subst(NULL
, tmp
, VAR_CMD
, 0);
1963 setenv("MAKEFLAGS", s
, 1);
1965 setenv("MAKE", s
, 1);
1973 static char *tmpdir
= NULL
;
1979 * Honor $TMPDIR but only if it is valid.
1980 * Ensure it ends with /.
1982 tmpdir
= Var_Subst(NULL
, "${TMPDIR:tA:U" _PATH_TMP
"}/", VAR_GLOBAL
, 0);
1983 if (stat(tmpdir
, &st
) < 0 || !S_ISDIR(st
.st_mode
)) {
1985 tmpdir
= bmake_strdup(_PATH_TMP
);
1992 * Create and open a temp file using "pattern".
1993 * If "fnamep" is provided set it to a copy of the filename created.
1994 * Otherwise unlink the file once open.
1997 mkTempFile(const char *pattern
, char **fnamep
)
1999 static char *tmpdir
= NULL
;
2000 char tfile
[MAXPATHLEN
];
2006 tmpdir
= getTmpdir();
2007 if (pattern
[0] == '/') {
2008 snprintf(tfile
, sizeof(tfile
), "%s", pattern
);
2010 snprintf(tfile
, sizeof(tfile
), "%s%s", tmpdir
, pattern
);
2012 if ((fd
= mkstemp(tfile
)) < 0)
2013 Punt("Could not create temporary file %s: %s", tfile
, strerror(errno
));
2015 *fnamep
= bmake_strdup(tfile
);
2017 unlink(tfile
); /* we just want the descriptor */