1 //===- SystemUtils.cpp - Utilities for low-level system tasks -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains functions used to do a variety of low-level, often
11 // system-specific, tasks.
13 //===----------------------------------------------------------------------===//
15 #define _POSIX_MAPPED_FILES
16 #include "Support/SystemUtils.h"
17 #include "Config/fcntl.h"
18 #include "Config/pagesize.h"
19 #include "Config/unistd.h"
20 #include "Config/windows.h"
21 #include "Config/sys/mman.h"
22 #include "Config/sys/stat.h"
23 #include "Config/sys/types.h"
24 #include "Config/sys/wait.h"
33 /// isExecutableFile - This function returns true if the filename specified
34 /// exists and is executable.
36 bool llvm::isExecutableFile(const std::string &ExeFileName) {
38 if (stat(ExeFileName.c_str(), &Buf))
39 return false; // Must not be executable!
41 if (!(Buf.st_mode & S_IFREG))
42 return false; // Not a regular file?
44 if (Buf.st_uid == getuid()) // Owner of file?
45 return Buf.st_mode & S_IXUSR;
46 else if (Buf.st_gid == getgid()) // In group of file?
47 return Buf.st_mode & S_IXGRP;
48 else // Unrelated to file?
49 return Buf.st_mode & S_IXOTH;
52 /// isStandardOutAConsole - Return true if we can tell that the standard output
53 /// stream goes to a terminal window or console.
54 bool llvm::isStandardOutAConsole() {
58 // If we don't have isatty, just return false.
63 /// FindExecutable - Find a named executable, giving the argv[0] of program
64 /// being executed. This allows us to find another LLVM tool if it is built
65 /// into the same directory, but that directory is neither the current
66 /// directory, nor in the PATH. If the executable cannot be found, return an
69 #undef FindExecutable // needed on windows :(
70 std::string llvm::FindExecutable(const std::string &ExeName,
71 const std::string &ProgramPath) {
72 // First check the directory that bugpoint is in. We can do this if
73 // BugPointPath contains at least one / character, indicating that it is a
74 // relative path to bugpoint itself.
76 std::string Result = ProgramPath;
77 while (!Result.empty() && Result[Result.size()-1] != '/')
78 Result.erase(Result.size()-1, 1);
80 if (!Result.empty()) {
82 if (isExecutableFile(Result)) return Result; // Found it?
85 // Okay, if the path to the program didn't tell us anything, try using the
86 // PATH environment variable.
87 const char *PathStr = getenv("PATH");
88 if (PathStr == 0) return "";
90 // Now we have a colon separated list of directories to search... try them...
91 unsigned PathLen = strlen(PathStr);
93 // Find the first colon...
94 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
96 // Check to see if this first directory contains the executable...
97 std::string FilePath = std::string(PathStr, Colon) + '/' + ExeName;
98 if (isExecutableFile(FilePath))
99 return FilePath; // Found the executable!
101 // Nope it wasn't in this directory, check the next range!
102 PathLen -= Colon-PathStr;
104 while (*PathStr == ':') { // Advance past colons
110 // If we fell out, we ran out of directories in PATH to search, return failure
114 static void RedirectFD(const std::string &File, int FD) {
115 if (File.empty()) return; // Noop
118 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
120 std::cerr << "Error opening file '" << File << "' for "
121 << (FD == 0 ? "input" : "output") << "!\n";
125 dup2(InFD, FD); // Install it as the requested FD
126 close(InFD); // Close the original FD
129 static bool Timeout = false;
130 static void TimeOutHandler(int Sig) {
134 /// RunProgramWithTimeout - This function executes the specified program, with
135 /// the specified null-terminated argument array, with the stdin/out/err fd's
136 /// redirected, with a timeout specified by the last argument. This terminates
137 /// the calling program if there is an error executing the specified program.
138 /// It returns the return value of the program, or -1 if a timeout is detected.
140 int llvm::RunProgramWithTimeout(const std::string &ProgramPath,
142 const std::string &StdInFile,
143 const std::string &StdOutFile,
144 const std::string &StdErrFile,
145 unsigned NumSeconds) {
146 #ifdef HAVE_SYS_WAIT_H
150 std::cerr << "ERROR forking!\n";
153 RedirectFD(StdInFile, 0); // Redirect file descriptors...
154 RedirectFD(StdOutFile, 1);
155 if (StdOutFile != StdErrFile)
156 RedirectFD(StdErrFile, 2);
160 execv(ProgramPath.c_str(), (char *const *)Args);
161 std::cerr << "Error executing program: '" << ProgramPath;
162 for (; *Args; ++Args)
163 std::cerr << " " << *Args;
170 // Make sure all output has been written while waiting
171 std::cout << std::flush;
173 // Install a timeout handler.
175 struct sigaction Act, Old;
176 Act.sa_sigaction = 0;
177 Act.sa_handler = TimeOutHandler;
178 sigemptyset(&Act.sa_mask);
180 sigaction(SIGALRM, &Act, &Old);
182 // Set the timeout if one is set.
187 while (wait(&Status) != Child)
188 if (errno == EINTR) {
191 kill(Child, SIGKILL);
193 if (wait(&Status) != Child)
194 std::cerr << "Something funny happened waiting for the child!\n";
197 sigaction(SIGALRM, &Old, 0);
198 return -1; // Timeout detected
200 std::cerr << "Error waiting for child process!\n";
206 sigaction(SIGALRM, &Old, 0);
210 std::cerr << "RunProgramWithTimeout not implemented on this platform!\n";
216 // ExecWait - executes a program with the specified arguments and environment.
217 // It then waits for the progarm to termiante and then returns to the caller.
220 // argv - The arguments to the program as an array of C strings. The first
221 // argument should be the name of the program to execute, and the
222 // last argument should be a pointer to NULL.
224 // envp - The environment passes to the program as an array of C strings in
225 // the form of "name=value" pairs. The last element should be a
233 // 1 - The program could not be executed.
234 // 1 - The program returned a non-zero exit status.
235 // 1 - The program terminated abnormally.
238 // The program will inherit the stdin, stdout, and stderr file descriptors
239 // as well as other various configuration settings (umask).
241 // This function should not print anything to stdout/stderr on its own. It is
242 // a generic library function. The caller or executed program should report
243 // errors in the way it sees fit.
245 // This function does not use $PATH to find programs.
247 int llvm::ExecWait(const char * const old_argv[],
248 const char * const old_envp[]) {
249 #ifdef HAVE_SYS_WAIT_H
250 // Create local versions of the parameters that can be passed into execve()
251 // without creating const problems.
252 char ** const argv = (char ** const) old_argv;
253 char ** const envp = (char ** const) old_envp;
255 // Create a child process.
257 // An error occured: Return to the caller.
262 // Child process: Execute the program.
264 execve (argv[0], argv, envp);
265 // If the execve() failed, we should exit and let the parent pick up
266 // our non-zero exit status.
269 // Parent process: Break out of the switch to do our processing.
274 // Parent process: Wait for the child process to terminate.
276 if ((wait (&status)) == -1)
279 // If the program exited normally with a zero exit status, return success!
280 if (WIFEXITED (status) && (WEXITSTATUS(status) == 0))
283 std::cerr << "llvm::ExecWait not implemented on this platform!\n";
286 // Otherwise, return failure.
290 /// AllocateRWXMemory - Allocate a slab of memory with read/write/execute
291 /// permissions. This is typically used for JIT applications where we want
292 /// to emit code to the memory then jump to it. Getting this type of memory
293 /// is very OS specific.
295 void *llvm::AllocateRWXMemory(unsigned NumBytes) {
296 if (NumBytes == 0) return 0;
298 #if defined(HAVE_WINDOWS_H)
299 // On windows we use VirtualAlloc.
300 void *P = VirtualAlloc(0, NumBytes, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
302 std::cerr << "Error allocating executable memory!\n";
307 #elif defined(HAVE_MMAP)
308 static const long pageSize = GetPageSize();
309 unsigned NumPages = (NumBytes+pageSize-1)/pageSize;
311 /* FIXME: This should use the proper autoconf flags */
312 #if defined(i386) || defined(__i386__) || defined(__x86__)
313 /* Linux and *BSD tend to have these flags named differently. */
314 #if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
315 # define MAP_ANONYMOUS MAP_ANON
316 #endif /* defined(MAP_ANON) && !defined(MAP_ANONYMOUS) */
317 #elif defined(sparc) || defined(__sparc__) || defined(__sparcv9)
320 std::cerr << "This architecture has an unknown MMAP implementation!\n";
326 #if defined(__linux__)
330 unsigned mmapFlags = MAP_PRIVATE|MAP_ANONYMOUS;
332 mmapFlags |= MAP_NORESERVE;
335 void *pa = mmap(0, pageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
337 if (pa == MAP_FAILED) {
343 std::cerr << "Do not know how to allocate mem for the JIT without mmap!\n";