improve haiku portability, patch by Paul Davey.
[oota-llvm.git] / lib / System / Unix / Program.inc
1 //===- llvm/System/Unix/Program.cpp -----------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Unix specific portion of the Program class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic UNIX code that
16 //===          is guaranteed to work on *all* UNIX variants.
17 //===----------------------------------------------------------------------===//
18
19 #include <llvm/Config/config.h>
20 #include "Unix.h"
21 #if HAVE_SYS_STAT_H
22 #include <sys/stat.h>
23 #endif
24 #if HAVE_SYS_RESOURCE_H
25 #include <sys/resource.h>
26 #endif
27 #if HAVE_SIGNAL_H
28 #include <signal.h>
29 #endif
30 #if HAVE_FCNTL_H
31 #include <fcntl.h>
32 #endif
33
34 namespace llvm {
35 using namespace sys;
36
37 Program::Program() : Data_(0) {}
38
39 Program::~Program() {}
40
41 unsigned Program::GetPid() const {
42   uint64_t pid = reinterpret_cast<uint64_t>(Data_);
43   return static_cast<unsigned>(pid);
44 }
45
46 // This function just uses the PATH environment variable to find the program.
47 Path
48 Program::FindProgramByName(const std::string& progName) {
49
50   // Check some degenerate cases
51   if (progName.length() == 0) // no program
52     return Path();
53   Path temp;
54   if (!temp.set(progName)) // invalid name
55     return Path();
56   // Use the given path verbatim if it contains any slashes; this matches
57   // the behavior of sh(1) and friends.
58   if (progName.find('/') != std::string::npos)
59     return temp;
60
61   // At this point, the file name does not contain slashes. Search for it
62   // through the directories specified in the PATH environment variable.
63
64   // Get the path. If its empty, we can't do anything to find it.
65   const char *PathStr = getenv("PATH");
66   if (PathStr == 0)
67     return Path();
68
69   // Now we have a colon separated list of directories to search; try them.
70   size_t PathLen = strlen(PathStr);
71   while (PathLen) {
72     // Find the first colon...
73     const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
74
75     // Check to see if this first directory contains the executable...
76     Path FilePath;
77     if (FilePath.set(std::string(PathStr,Colon))) {
78       FilePath.appendComponent(progName);
79       if (FilePath.canExecute())
80         return FilePath;                    // Found the executable!
81     }
82
83     // Nope it wasn't in this directory, check the next path in the list!
84     PathLen -= Colon-PathStr;
85     PathStr = Colon;
86
87     // Advance past duplicate colons
88     while (*PathStr == ':') {
89       PathStr++;
90       PathLen--;
91     }
92   }
93   return Path();
94 }
95
96 static bool RedirectIO(const Path *Path, int FD, std::string* ErrMsg) {
97   if (Path == 0)
98     // Noop
99     return false;
100   std::string File;
101   if (Path->isEmpty())
102     // Redirect empty paths to /dev/null
103     File = "/dev/null";
104   else
105     File = Path->str();
106
107   // Open the file
108   int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
109   if (InFD == -1) {
110     MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
111               + (FD == 0 ? "input" : "output"));
112     return true;
113   }
114
115   // Install it as the requested FD
116   if (dup2(InFD, FD) == -1) {
117     MakeErrMsg(ErrMsg, "Cannot dup2");
118     close(InFD);
119     return true;
120   }
121   close(InFD);      // Close the original FD
122   return false;
123 }
124
125 static void TimeOutHandler(int Sig) {
126 }
127
128 static void SetMemoryLimits (unsigned size)
129 {
130 #if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
131   struct rlimit r;
132   __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
133
134   // Heap size
135   getrlimit (RLIMIT_DATA, &r);
136   r.rlim_cur = limit;
137   setrlimit (RLIMIT_DATA, &r);
138 #ifdef RLIMIT_RSS
139   // Resident set size.
140   getrlimit (RLIMIT_RSS, &r);
141   r.rlim_cur = limit;
142   setrlimit (RLIMIT_RSS, &r);
143 #endif
144 #ifdef RLIMIT_AS  // e.g. NetBSD doesn't have it.
145   // Virtual memory.
146   getrlimit (RLIMIT_AS, &r);
147   r.rlim_cur = limit;
148   setrlimit (RLIMIT_AS, &r);
149 #endif
150 #endif
151 }
152
153 bool
154 Program::Execute(const Path& path,
155                  const char** args,
156                  const char** envp,
157                  const Path** redirects,
158                  unsigned memoryLimit,
159                  std::string* ErrMsg)
160 {
161   if (!path.canExecute()) {
162     if (ErrMsg)
163       *ErrMsg = path.str() + " is not executable";
164     return false;
165   }
166
167   // Create a child process.
168   int child = fork();
169   switch (child) {
170     // An error occured:  Return to the caller.
171     case -1:
172       MakeErrMsg(ErrMsg, "Couldn't fork");
173       return false;
174
175     // Child process: Execute the program.
176     case 0: {
177       // Redirect file descriptors...
178       if (redirects) {
179         // Redirect stdin
180         if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
181         // Redirect stdout
182         if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
183         if (redirects[1] && redirects[2] &&
184             *(redirects[1]) == *(redirects[2])) {
185           // If stdout and stderr should go to the same place, redirect stderr
186           // to the FD already open for stdout.
187           if (-1 == dup2(1,2)) {
188             MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
189             return false;
190           }
191         } else {
192           // Just redirect stderr
193           if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
194         }
195       }
196
197       // Set memory limits
198       if (memoryLimit!=0) {
199         SetMemoryLimits(memoryLimit);
200       }
201
202       // Execute!
203       if (envp != 0)
204         execve(path.c_str(), (char**)args, (char**)envp);
205       else
206         execv(path.c_str(), (char**)args);
207       // If the execve() failed, we should exit. Follow Unix protocol and
208       // return 127 if the executable was not found, and 126 otherwise.
209       // Use _exit rather than exit so that atexit functions and static
210       // object destructors cloned from the parent process aren't
211       // redundantly run, and so that any data buffered in stdio buffers
212       // cloned from the parent aren't redundantly written out.
213       _exit(errno == ENOENT ? 127 : 126);
214     }
215
216     // Parent process: Break out of the switch to do our processing.
217     default:
218       break;
219   }
220
221   Data_ = reinterpret_cast<void*>(child);
222
223   return true;
224 }
225
226 int
227 Program::Wait(unsigned secondsToWait,
228               std::string* ErrMsg)
229 {
230 #ifdef HAVE_SYS_WAIT_H
231   struct sigaction Act, Old;
232
233   if (Data_ == 0) {
234     MakeErrMsg(ErrMsg, "Process not started!");
235     return -1;
236   }
237
238   // Install a timeout handler.  The handler itself does nothing, but the simple
239   // fact of having a handler at all causes the wait below to return with EINTR,
240   // unlike if we used SIG_IGN.
241   if (secondsToWait) {
242 #ifndef __HAIKU__
243     Act.sa_sigaction = 0;
244 #endif
245     Act.sa_handler = TimeOutHandler;
246     sigemptyset(&Act.sa_mask);
247     Act.sa_flags = 0;
248     sigaction(SIGALRM, &Act, &Old);
249     alarm(secondsToWait);
250   }
251
252   // Parent process: Wait for the child process to terminate.
253   int status;
254   uint64_t pid = reinterpret_cast<uint64_t>(Data_);
255   pid_t child = static_cast<pid_t>(pid);
256   while (waitpid(pid, &status, 0) != child)
257     if (secondsToWait && errno == EINTR) {
258       // Kill the child.
259       kill(child, SIGKILL);
260
261       // Turn off the alarm and restore the signal handler
262       alarm(0);
263       sigaction(SIGALRM, &Old, 0);
264
265       // Wait for child to die
266       if (wait(&status) != child)
267         MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
268       else
269         MakeErrMsg(ErrMsg, "Child timed out", 0);
270
271       return -1;   // Timeout detected
272     } else if (errno != EINTR) {
273       MakeErrMsg(ErrMsg, "Error waiting for child process");
274       return -1;
275     }
276
277   // We exited normally without timeout, so turn off the timer.
278   if (secondsToWait) {
279     alarm(0);
280     sigaction(SIGALRM, &Old, 0);
281   }
282
283   // Return the proper exit status. 0=success, >0 is programs' exit status,
284   // <0 means a signal was returned, -9999999 means the program dumped core.
285   int result = 0;
286   if (WIFEXITED(status))
287     result = WEXITSTATUS(status);
288   else if (WIFSIGNALED(status))
289     result = 0 - WTERMSIG(status);
290 #ifdef WCOREDUMP
291   else if (WCOREDUMP(status))
292     result |= 0x01000000;
293 #endif
294   return result;
295 #else
296   return -99;
297 #endif
298
299 }
300
301 bool
302 Program::Kill(std::string* ErrMsg) {
303   if (Data_ == 0) {
304     MakeErrMsg(ErrMsg, "Process not started!");
305     return true;
306   }
307
308   uint64_t pid64 = reinterpret_cast<uint64_t>(Data_);
309   pid_t pid = static_cast<pid_t>(pid64);
310
311   if (kill(pid, SIGKILL) != 0) {
312     MakeErrMsg(ErrMsg, "The process couldn't be killed!");
313     return true;
314   }
315
316   return false;
317 }
318
319 bool Program::ChangeStdinToBinary(){
320   // Do nothing, as Unix doesn't differentiate between text and binary.
321   return false;
322 }
323
324 bool Program::ChangeStdoutToBinary(){
325   // Do nothing, as Unix doesn't differentiate between text and binary.
326   return false;
327 }
328
329 bool Program::ChangeStderrToBinary(){
330   // Do nothing, as Unix doesn't differentiate between text and binary.
331   return false;
332 }
333
334 }