Changes For Bug 352
[oota-llvm.git] / lib / Support / SystemUtils.cpp
1 //===- SystemUtils.cpp - Utilities for low-level system tasks -------------===//
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 "llvm/Support/SystemUtils.h"
17 #include "llvm/Config/fcntl.h"
18 #include "llvm/Config/pagesize.h"
19 #include "llvm/Config/unistd.h"
20 #include "llvm/Config/windows.h"
21 #include "llvm/Config/sys/mman.h"
22 #include "llvm/Config/sys/stat.h"
23 #include "llvm/Config/sys/types.h"
24 #include "llvm/Config/sys/wait.h"
25 #include <algorithm>
26 #include <cerrno>
27 #include <cstdlib>
28 #include <fstream>
29 #include <iostream>
30 #include <signal.h>
31 using namespace llvm;
32
33 /// isExecutableFile - This function returns true if the filename specified
34 /// exists and is executable.
35 ///
36 bool llvm::isExecutableFile(const std::string &ExeFileName) {
37   struct stat Buf;
38   if (stat(ExeFileName.c_str(), &Buf))
39     return false;  // Must not be executable!
40
41   if (!(Buf.st_mode & S_IFREG))
42     return false;                    // Not a regular file?
43
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;
50 }
51
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() {
55 #if HAVE_ISATTY
56   return isatty(1);
57 #endif
58   // If we don't have isatty, just return false.
59   return false;
60 }
61
62
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
67 /// empty string.
68 /// 
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.
75   //
76   std::string Result = ProgramPath;
77   while (!Result.empty() && Result[Result.size()-1] != '/')
78     Result.erase(Result.size()-1, 1);
79
80   if (!Result.empty()) {
81     Result += ExeName;
82     if (isExecutableFile(Result)) return Result; // Found it?
83   }
84
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 "";
89
90   // Now we have a colon separated list of directories to search... try them...
91   unsigned PathLen = strlen(PathStr);
92   while (PathLen) {
93     // Find the first colon...
94     const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
95     
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!
100    
101     // Nope it wasn't in this directory, check the next range!
102     PathLen -= Colon-PathStr;
103     PathStr = Colon;
104     while (*PathStr == ':') {   // Advance past colons
105       PathStr++;
106       PathLen--;
107     }
108   }
109
110   // If we fell out, we ran out of directories in PATH to search, return failure
111   return "";
112 }
113
114 static void RedirectFD(const std::string &File, int FD) {
115   if (File.empty()) return;  // Noop
116
117   // Open the file
118   int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
119   if (InFD == -1) {
120     std::cerr << "Error opening file '" << File << "' for "
121               << (FD == 0 ? "input" : "output") << "!\n";
122     exit(1);
123   }
124
125   dup2(InFD, FD);   // Install it as the requested FD
126   close(InFD);      // Close the original FD
127 }
128
129 static bool Timeout = false;
130 static void TimeOutHandler(int Sig) {
131   Timeout = true;
132 }
133
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.
139 ///
140 int llvm::RunProgramWithTimeout(const std::string &ProgramPath,
141                                 const char **Args,
142                                 const std::string &StdInFile,
143                                 const std::string &StdOutFile,
144                                 const std::string &StdErrFile,
145                                 unsigned NumSeconds) {
146 #ifdef HAVE_SYS_WAIT_H
147   int Child = fork();
148   switch (Child) {
149   case -1:
150     std::cerr << "ERROR forking!\n";
151     exit(1);
152   case 0:               // Child
153     RedirectFD(StdInFile, 0);      // Redirect file descriptors...
154     RedirectFD(StdOutFile, 1);
155     if (StdOutFile != StdErrFile)
156       RedirectFD(StdErrFile, 2);
157     else
158       dup2(1, 2);
159
160     execv(ProgramPath.c_str(), (char *const *)Args);
161     std::cerr << "Error executing program: '" << ProgramPath;
162     for (; *Args; ++Args)
163       std::cerr << " " << *Args;
164     std::cerr << "'\n";
165     exit(1);
166
167   default: break;
168   }
169
170   // Make sure all output has been written while waiting
171   std::cout << std::flush;
172
173   // Install a timeout handler.
174   Timeout = false;
175   struct sigaction Act, Old;
176   Act.sa_sigaction = 0;
177   Act.sa_handler = TimeOutHandler;
178   sigemptyset(&Act.sa_mask);
179   Act.sa_flags = 0;
180   sigaction(SIGALRM, &Act, &Old);
181
182   // Set the timeout if one is set.
183   if (NumSeconds)
184     alarm(NumSeconds);
185
186   int Status;
187   while (wait(&Status) != Child)
188     if (errno == EINTR) {
189       if (Timeout) {
190         // Kill the child.
191         kill(Child, SIGKILL);
192         
193         if (wait(&Status) != Child)
194           std::cerr << "Something funny happened waiting for the child!\n";
195         
196         alarm(0);
197         sigaction(SIGALRM, &Old, 0);
198         return -1;   // Timeout detected
199       } else {
200         std::cerr << "Error waiting for child process!\n";
201         exit(1);
202       }
203     }
204
205   alarm(0);
206   sigaction(SIGALRM, &Old, 0);
207   return Status;
208
209 #else
210   std::cerr << "RunProgramWithTimeout not implemented on this platform!\n";
211   return -1;
212 #endif
213 }
214
215
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.
218 //
219 // Inputs:
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.
223 //
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
226 //         pointer to NULL.
227 //
228 // Outputs:
229 //  None.
230 //
231 // Return value:
232 //  0 - No errors.
233 //  1 - The program could not be executed.
234 //  1 - The program returned a non-zero exit status.
235 //  1 - The program terminated abnormally.
236 //
237 // Notes:
238 //  The program will inherit the stdin, stdout, and stderr file descriptors
239 //  as well as other various configuration settings (umask).
240 //
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.
244 //
245 //  This function does not use $PATH to find programs.
246 //
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;
254
255   // Create a child process.
256   switch (fork()) {
257     // An error occured:  Return to the caller.
258     case -1:
259       return 1;
260       break;
261
262     // Child process: Execute the program.
263     case 0:
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.
267       exit (1);
268
269     // Parent process: Break out of the switch to do our processing.
270     default:
271       break;
272   }
273
274   // Parent process: Wait for the child process to terminate.
275   int status;
276   if ((wait (&status)) == -1)
277     return 1;
278
279   // If the program exited normally with a zero exit status, return success!
280   if (WIFEXITED (status) && (WEXITSTATUS(status) == 0))
281     return 0;
282 #else
283   std::cerr << "llvm::ExecWait not implemented on this platform!\n";
284 #endif
285
286   // Otherwise, return failure.
287   return 1;
288 }
289
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.
294 ///
295 void *llvm::AllocateRWXMemory(unsigned NumBytes) {
296   if (NumBytes == 0) return 0;
297
298 #if defined(HAVE_WINDOWS_H)
299   // On windows we use VirtualAlloc.
300   void *P = VirtualAlloc(0, NumBytes, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
301   if (P == 0) {
302     std::cerr << "Error allocating executable memory!\n";
303     abort();
304   }
305   return P;
306
307 #elif defined(HAVE_MMAP)
308   static const long pageSize = GetPageSize();
309   unsigned NumPages = (NumBytes+pageSize-1)/pageSize;
310
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)
318 /* nothing */
319 #else
320   std::cerr << "This architecture has an unknown MMAP implementation!\n";
321   abort();
322   return 0;
323 #endif
324
325   int fd = -1;
326 #if defined(__linux__)
327   fd = 0;
328 #endif
329
330   unsigned mmapFlags = MAP_PRIVATE|MAP_ANONYMOUS;
331 #ifdef MAP_NORESERVE
332   mmapFlags |= MAP_NORESERVE;
333 #endif
334
335   void *pa = mmap(0, pageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
336                   mmapFlags, fd, 0);
337   if (pa == MAP_FAILED) {
338     perror("mmap");
339     abort();
340   }
341   return pa;
342 #else
343   std::cerr << "Do not know how to allocate mem for the JIT without mmap!\n";
344   abort();
345   return 0;
346 #endif
347 }
348
349