1 //===- SystemUtils.h - Utilities to do low-level system stuff --*- C++ -*--===//
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/sys/types.h"
18 #include "Config/sys/stat.h"
19 #include "Config/fcntl.h"
20 #include "Config/sys/wait.h"
21 #include "Config/sys/mman.h"
22 #include "Config/unistd.h"
28 #include "Config/windows.h"
31 /// isExecutableFile - This function returns true if the filename specified
32 /// exists and is executable.
34 bool llvm::isExecutableFile(const std::string &ExeFileName) {
36 if (stat(ExeFileName.c_str(), &Buf))
37 return false; // Must not be executable!
39 if (!(Buf.st_mode & S_IFREG))
40 return false; // Not a regular file?
42 if (Buf.st_uid == getuid()) // Owner of file?
43 return Buf.st_mode & S_IXUSR;
44 else if (Buf.st_gid == getgid()) // In group of file?
45 return Buf.st_mode & S_IXGRP;
46 else // Unrelated to file?
47 return Buf.st_mode & S_IXOTH;
50 /// isStandardOutAConsole - Return true if we can tell that the standard output
51 /// stream goes to a terminal window or console.
52 bool llvm::isStandardOutAConsole() {
56 // If we don't have isatty, just return false.
61 /// FindExecutable - Find a named executable, giving the argv[0] of program
62 /// being executed. This allows us to find another LLVM tool if it is built
63 /// into the same directory, but that directory is neither the current
64 /// directory, nor in the PATH. If the executable cannot be found, return an
67 #undef FindExecutable // needed on windows :(
68 std::string llvm::FindExecutable(const std::string &ExeName,
69 const std::string &ProgramPath) {
70 // First check the directory that bugpoint is in. We can do this if
71 // BugPointPath contains at least one / character, indicating that it is a
72 // relative path to bugpoint itself.
74 std::string Result = ProgramPath;
75 while (!Result.empty() && Result[Result.size()-1] != '/')
76 Result.erase(Result.size()-1, 1);
78 if (!Result.empty()) {
80 if (isExecutableFile(Result)) return Result; // Found it?
83 // Okay, if the path to the program didn't tell us anything, try using the
84 // PATH environment variable.
85 const char *PathStr = getenv("PATH");
86 if (PathStr == 0) return "";
88 // Now we have a colon separated list of directories to search... try them...
89 unsigned PathLen = strlen(PathStr);
91 // Find the first colon...
92 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
94 // Check to see if this first directory contains the executable...
95 std::string FilePath = std::string(PathStr, Colon) + '/' + ExeName;
96 if (isExecutableFile(FilePath))
97 return FilePath; // Found the executable!
99 // Nope it wasn't in this directory, check the next range!
100 PathLen -= Colon-PathStr;
102 while (*PathStr == ':') { // Advance past colons
108 // If we fell out, we ran out of directories in PATH to search, return failure
112 static void RedirectFD(const std::string &File, int FD) {
113 if (File.empty()) return; // Noop
116 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
118 std::cerr << "Error opening file '" << File << "' for "
119 << (FD == 0 ? "input" : "output") << "!\n";
123 dup2(InFD, FD); // Install it as the requested FD
124 close(InFD); // Close the original FD
127 /// RunProgramWithTimeout - This function executes the specified program, with
128 /// the specified null-terminated argument array, with the stdin/out/err fd's
129 /// redirected, with a timeout specified on the command line. This terminates
130 /// the calling program if there is an error executing the specified program.
131 /// It returns the return value of the program, or -1 if a timeout is detected.
133 int llvm::RunProgramWithTimeout(const std::string &ProgramPath,
135 const std::string &StdInFile,
136 const std::string &StdOutFile,
137 const std::string &StdErrFile) {
138 // FIXME: install sigalarm handler here for timeout...
140 #ifdef HAVE_SYS_WAIT_H
144 std::cerr << "ERROR forking!\n";
147 RedirectFD(StdInFile, 0); // Redirect file descriptors...
148 RedirectFD(StdOutFile, 1);
149 if (StdOutFile != StdErrFile)
150 RedirectFD(StdErrFile, 2);
154 execv(ProgramPath.c_str(), (char *const *)Args);
155 std::cerr << "Error executing program: '" << ProgramPath;
156 for (; *Args; ++Args)
157 std::cerr << " " << *Args;
164 // Make sure all output has been written while waiting
165 std::cout << std::flush;
168 if (wait(&Status) != Child) {
169 if (errno == EINTR) {
170 static bool FirstTimeout = true;
173 "*** Program execution timed out! This mechanism is designed to handle\n"
174 " programs stuck in infinite loops gracefully. The -timeout option\n"
175 " can be used to change the timeout threshold or disable it completely\n"
176 " (with -timeout=0). This message is only displayed once.\n";
177 FirstTimeout = false;
179 return -1; // Timeout detected
182 std::cerr << "Error waiting for child process!\n";
188 std::cerr << "RunProgramWithTimeout not implemented on this platform!\n";
194 // ExecWait - executes a program with the specified arguments and environment.
195 // It then waits for the progarm to termiante and then returns to the caller.
198 // argv - The arguments to the program as an array of C strings. The first
199 // argument should be the name of the program to execute, and the
200 // last argument should be a pointer to NULL.
202 // envp - The environment passes to the program as an array of C strings in
203 // the form of "name=value" pairs. The last element should be a
211 // 1 - The program could not be executed.
212 // 1 - The program returned a non-zero exit status.
213 // 1 - The program terminated abnormally.
216 // The program will inherit the stdin, stdout, and stderr file descriptors
217 // as well as other various configuration settings (umask).
219 // This function should not print anything to stdout/stderr on its own. It is
220 // a generic library function. The caller or executed program should report
221 // errors in the way it sees fit.
223 // This function does not use $PATH to find programs.
225 int llvm::ExecWait(const char * const old_argv[],
226 const char * const old_envp[]) {
227 #ifdef HAVE_SYS_WAIT_H
228 // Create local versions of the parameters that can be passed into execve()
229 // without creating const problems.
230 char ** const argv = (char ** const) old_argv;
231 char ** const envp = (char ** const) old_envp;
233 // Create a child process.
235 // An error occured: Return to the caller.
240 // Child process: Execute the program.
242 execve (argv[0], argv, envp);
243 // If the execve() failed, we should exit and let the parent pick up
244 // our non-zero exit status.
247 // Parent process: Break out of the switch to do our processing.
252 // Parent process: Wait for the child process to terminate.
254 if ((wait (&status)) == -1)
257 // If the program exited normally with a zero exit status, return success!
258 if (WIFEXITED (status) && (WEXITSTATUS(status) == 0))
261 std::cerr << "llvm::ExecWait not implemented on this platform!\n";
264 // Otherwise, return failure.
268 /// AllocateRWXMemory - Allocate a slab of memory with read/write/execute
269 /// permissions. This is typically used for JIT applications where we want
270 /// to emit code to the memory then jump to it. Getting this type of memory
271 /// is very OS specific.
273 void *llvm::AllocateRWXMemory(unsigned NumBytes) {
274 if (NumBytes == 0) return 0;
276 #if defined(HAVE_WINDOWS_H)
277 // On windows we use VirtualAlloc.
278 void *P = VirtualAlloc(0, NumBytes, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
280 std::cerr << "Error allocating executable memory!\n";
285 #elif defined(HAVE_MMAP)
286 static const long pageSize = sysconf(_SC_PAGESIZE);
287 unsigned NumPages = (NumBytes+pageSize-1)/pageSize;
289 /* FIXME: This should use the proper autoconf flags */
290 #if defined(i386) || defined(__i386__) || defined(__x86__)
291 /* Linux and *BSD tend to have these flags named differently. */
292 #if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
293 # define MAP_ANONYMOUS MAP_ANON
294 #endif /* defined(MAP_ANON) && !defined(MAP_ANONYMOUS) */
295 #elif defined(sparc) || defined(__sparc__) || defined(__sparcv9)
298 std::cerr << "This architecture has an unknown MMAP implementation!\n";
304 #if defined(__linux__)
308 unsigned mmapFlags = MAP_PRIVATE|MAP_ANONYMOUS;
310 mmapFlags |= MAP_NORESERVE;
313 void *pa = mmap(0, pageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
315 if (pa == MAP_FAILED) {
321 std::cerr << "Do not know how to allocate mem for the JIT without mmap!\n";