076e3a7b9330f112439bbef27d0286735dda117f
[oota-llvm.git] / lib / Support / SystemUtils.cpp
1 //===- SystemUtils.h - Utilities to do low-level system stuff --*- C++ -*--===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains functions used to do a variety of low-level, often
11 // system-specific, tasks.
12 //
13 //===----------------------------------------------------------------------===//
14
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"
23 #include <algorithm>
24 #include <fstream>
25 #include <iostream>
26 #include <cstdlib>
27 #include <cerrno>
28 #include "Config/windows.h"
29 using namespace llvm;
30
31 /// isExecutableFile - This function returns true if the filename specified
32 /// exists and is executable.
33 ///
34 bool llvm::isExecutableFile(const std::string &ExeFileName) {
35   struct stat Buf;
36   if (stat(ExeFileName.c_str(), &Buf))
37     return false;  // Must not be executable!
38
39   if (!(Buf.st_mode & S_IFREG))
40     return false;                    // Not a regular file?
41
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;
48 }
49
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() {
53 #if HAVE_ISATTY
54   return isatty(1);
55 #endif
56   // If we don't have isatty, just return false.
57   return false;
58 }
59
60
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
65 /// empty string.
66 /// 
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.
73   //
74   std::string Result = ProgramPath;
75   while (!Result.empty() && Result[Result.size()-1] != '/')
76     Result.erase(Result.size()-1, 1);
77
78   if (!Result.empty()) {
79     Result += ExeName;
80     if (isExecutableFile(Result)) return Result; // Found it?
81   }
82
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 "";
87
88   // Now we have a colon separated list of directories to search... try them...
89   unsigned PathLen = strlen(PathStr);
90   while (PathLen) {
91     // Find the first colon...
92     const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
93     
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!
98    
99     // Nope it wasn't in this directory, check the next range!
100     PathLen -= Colon-PathStr;
101     PathStr = Colon;
102     while (*PathStr == ':') {   // Advance past colons
103       PathStr++;
104       PathLen--;
105     }
106   }
107
108   // If we fell out, we ran out of directories in PATH to search, return failure
109   return "";
110 }
111
112 static void RedirectFD(const std::string &File, int FD) {
113   if (File.empty()) return;  // Noop
114
115   // Open the file
116   int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
117   if (InFD == -1) {
118     std::cerr << "Error opening file '" << File << "' for "
119               << (FD == 0 ? "input" : "output") << "!\n";
120     exit(1);
121   }
122
123   dup2(InFD, FD);   // Install it as the requested FD
124   close(InFD);      // Close the original FD
125 }
126
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.
132 ///
133 int llvm::RunProgramWithTimeout(const std::string &ProgramPath,
134                                 const char **Args,
135                                 const std::string &StdInFile,
136                                 const std::string &StdOutFile,
137                                 const std::string &StdErrFile) {
138   // FIXME: install sigalarm handler here for timeout...
139
140 #ifdef HAVE_SYS_WAIT_H
141   int Child = fork();
142   switch (Child) {
143   case -1:
144     std::cerr << "ERROR forking!\n";
145     exit(1);
146   case 0:               // Child
147     RedirectFD(StdInFile, 0);      // Redirect file descriptors...
148     RedirectFD(StdOutFile, 1);
149     if (StdOutFile != StdErrFile)
150       RedirectFD(StdErrFile, 2);
151     else
152       dup2(1, 2);
153
154     execv(ProgramPath.c_str(), (char *const *)Args);
155     std::cerr << "Error executing program: '" << ProgramPath;
156     for (; *Args; ++Args)
157       std::cerr << " " << *Args;
158     std::cerr << "'\n";
159     exit(1);
160
161   default: break;
162   }
163
164   // Make sure all output has been written while waiting
165   std::cout << std::flush;
166
167   int Status;
168   if (wait(&Status) != Child) {
169     if (errno == EINTR) {
170       static bool FirstTimeout = true;
171       if (FirstTimeout) {
172         std::cout <<
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;
178       }
179       return -1;   // Timeout detected
180     }
181
182     std::cerr << "Error waiting for child process!\n";
183     exit(1);
184   }
185   return Status;
186
187 #else
188   std::cerr << "RunProgramWithTimeout not implemented on this platform!\n";
189   return -1;
190 #endif
191 }
192
193
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.
196 //
197 // Inputs:
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.
201 //
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
204 //         pointer to NULL.
205 //
206 // Outputs:
207 //  None.
208 //
209 // Return value:
210 //  0 - No errors.
211 //  1 - The program could not be executed.
212 //  1 - The program returned a non-zero exit status.
213 //  1 - The program terminated abnormally.
214 //
215 // Notes:
216 //  The program will inherit the stdin, stdout, and stderr file descriptors
217 //  as well as other various configuration settings (umask).
218 //
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.
222 //
223 //  This function does not use $PATH to find programs.
224 //
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;
232
233   // Create a child process.
234   switch (fork()) {
235     // An error occured:  Return to the caller.
236     case -1:
237       return 1;
238       break;
239
240     // Child process: Execute the program.
241     case 0:
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.
245       exit (1);
246
247     // Parent process: Break out of the switch to do our processing.
248     default:
249       break;
250   }
251
252   // Parent process: Wait for the child process to terminate.
253   int status;
254   if ((wait (&status)) == -1)
255     return 1;
256
257   // If the program exited normally with a zero exit status, return success!
258   if (WIFEXITED (status) && (WEXITSTATUS(status) == 0))
259     return 0;
260 #else
261   std::cerr << "llvm::ExecWait not implemented on this platform!\n";
262 #endif
263
264   // Otherwise, return failure.
265   return 1;
266 }
267
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.
272 ///
273 void *llvm::AllocateRWXMemory(unsigned NumBytes) {
274   if (NumBytes == 0) return 0;
275
276 #if defined(HAVE_WINDOWS_H)
277   // On windows we use VirtualAlloc.
278   void *P = VirtualAlloc(0, NumBytes, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
279   if (P == 0) {
280     std::cerr << "Error allocating executable memory!\n";
281     abort();
282   }
283   return P;
284
285 #elif defined(HAVE_MMAP)
286   static const long pageSize = sysconf(_SC_PAGESIZE);
287   unsigned NumPages = (NumBytes+pageSize-1)/pageSize;
288
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)
296 /* nothing */
297 #else
298   std::cerr << "This architecture has an unknown MMAP implementation!\n";
299   abort();
300   return 0;
301 #endif
302
303   int fd = -1;
304 #if defined(__linux__)
305   fd = 0;
306 #endif
307
308   unsigned mmapFlags = MAP_PRIVATE|MAP_ANONYMOUS;
309 #ifdef MAP_NORESERVE
310   mmapFlags |= MAP_NORESERVE;
311 #endif
312
313   void *pa = mmap(0, pageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
314                   mmapFlags, fd, 0);
315   if (pa == MAP_FAILED) {
316     perror("mmap");
317     abort();
318   }
319   return pa;
320 #else
321   std::cerr << "Do not know how to allocate mem for the JIT without mmap!\n";
322   abort();
323   return 0;
324 #endif
325 }
326
327