c52f3a88c044403f9aaa325a57737511eea63066
[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 (-1 == dup2(InFD, FD)) {
117     MakeErrMsg(ErrMsg, "Cannot dup2");
118     return true;
119   }
120   close(InFD);      // Close the original FD
121   return false;
122 }
123
124 static void SetMemoryLimits (unsigned size)
125 {
126 #if HAVE_SYS_RESOURCE_H
127   struct rlimit r;
128   __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
129
130   // Heap size
131   getrlimit (RLIMIT_DATA, &r);
132   r.rlim_cur = limit;
133   setrlimit (RLIMIT_DATA, &r);
134 #ifdef RLIMIT_RSS
135   // Resident set size.
136   getrlimit (RLIMIT_RSS, &r);
137   r.rlim_cur = limit;
138   setrlimit (RLIMIT_RSS, &r);
139 #endif
140 #ifdef RLIMIT_AS  // e.g. NetBSD doesn't have it.
141   // Virtual memory.
142   getrlimit (RLIMIT_AS, &r);
143   r.rlim_cur = limit;
144   setrlimit (RLIMIT_AS, &r);
145 #endif
146 #endif
147 }
148
149 bool
150 Program::Execute(const Path& path,
151                  const char** args,
152                  const char** envp,
153                  const Path** redirects,
154                  unsigned memoryLimit,
155                  std::string* ErrMsg)
156 {
157   if (!path.canExecute()) {
158     if (ErrMsg)
159       *ErrMsg = path.str() + " is not executable";
160     return false;
161   }
162
163   // Create a child process.
164   int child = fork();
165   switch (child) {
166     // An error occured:  Return to the caller.
167     case -1:
168       MakeErrMsg(ErrMsg, "Couldn't fork");
169       return false;
170
171     // Child process: Execute the program.
172     case 0: {
173       // Redirect file descriptors...
174       if (redirects) {
175         // Redirect stdin
176         if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
177         // Redirect stdout
178         if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
179         if (redirects[1] && redirects[2] &&
180             *(redirects[1]) == *(redirects[2])) {
181           // If stdout and stderr should go to the same place, redirect stderr
182           // to the FD already open for stdout.
183           if (-1 == dup2(1,2)) {
184             MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
185             return false;
186           }
187         } else {
188           // Just redirect stderr
189           if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
190         }
191       }
192
193       // Set memory limits
194       if (memoryLimit!=0) {
195         SetMemoryLimits(memoryLimit);
196       }
197
198       // Execute!
199       if (envp != 0)
200         execve(path.c_str(), (char**)args, (char**)envp);
201       else
202         execv(path.c_str(), (char**)args);
203       // If the execve() failed, we should exit. Follow Unix protocol and
204       // return 127 if the executable was not found, and 126 otherwise.
205       // Use _exit rather than exit so that atexit functions and static
206       // object destructors cloned from the parent process aren't
207       // redundantly run, and so that any data buffered in stdio buffers
208       // cloned from the parent aren't redundantly written out.
209       _exit(errno == ENOENT ? 127 : 126);
210     }
211
212     // Parent process: Break out of the switch to do our processing.
213     default:
214       break;
215   }
216
217   Data_ = reinterpret_cast<void*>(child);
218
219   return true;
220 }
221
222 int
223 Program::Wait(unsigned secondsToWait,
224               std::string* ErrMsg)
225 {
226 #ifdef HAVE_SYS_WAIT_H
227   struct sigaction Act, Old;
228
229   if (Data_ == 0) {
230     MakeErrMsg(ErrMsg, "Process not started!");
231     return -1;
232   }
233
234   // Install a timeout handler.
235   if (secondsToWait) {
236     memset(&Act, 0, sizeof(Act));
237     Act.sa_handler = SIG_IGN;
238     sigemptyset(&Act.sa_mask);
239     sigaction(SIGALRM, &Act, &Old);
240     alarm(secondsToWait);
241   }
242
243   // Parent process: Wait for the child process to terminate.
244   int status;
245   uint64_t pid = reinterpret_cast<uint64_t>(Data_);
246   pid_t child = static_cast<pid_t>(pid);
247   while (waitpid(pid, &status, 0) != child)
248     if (secondsToWait && errno == EINTR) {
249       // Kill the child.
250       kill(child, SIGKILL);
251
252       // Turn off the alarm and restore the signal handler
253       alarm(0);
254       sigaction(SIGALRM, &Old, 0);
255
256       // Wait for child to die
257       if (wait(&status) != child)
258         MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
259       else
260         MakeErrMsg(ErrMsg, "Child timed out", 0);
261
262       return -1;   // Timeout detected
263     } else if (errno != EINTR) {
264       MakeErrMsg(ErrMsg, "Error waiting for child process");
265       return -1;
266     }
267
268   // We exited normally without timeout, so turn off the timer.
269   if (secondsToWait) {
270     alarm(0);
271     sigaction(SIGALRM, &Old, 0);
272   }
273
274   // Return the proper exit status. 0=success, >0 is programs' exit status,
275   // <0 means a signal was returned, -9999999 means the program dumped core.
276   int result = 0;
277   if (WIFEXITED(status))
278     result = WEXITSTATUS(status);
279   else if (WIFSIGNALED(status))
280     result = 0 - WTERMSIG(status);
281 #ifdef WCOREDUMP
282   else if (WCOREDUMP(status))
283     result |= 0x01000000;
284 #endif
285   return result;
286 #else
287   return -99;
288 #endif
289
290 }
291
292 bool
293 Program::Kill(std::string* ErrMsg) {
294   if (Data_ == 0) {
295     MakeErrMsg(ErrMsg, "Process not started!");
296     return true;
297   }
298
299   uint64_t pid64 = reinterpret_cast<uint64_t>(Data_);
300   pid_t pid = static_cast<pid_t>(pid64);
301
302   if (kill(pid, SIGKILL) != 0) {
303     MakeErrMsg(ErrMsg, "The process couldn't be killed!");
304     return true;
305   }
306
307   return false;
308 }
309
310 bool Program::ChangeStdinToBinary(){
311   // Do nothing, as Unix doesn't differentiate between text and binary.
312   return false;
313 }
314
315 bool Program::ChangeStdoutToBinary(){
316   // Do nothing, as Unix doesn't differentiate between text and binary.
317   return false;
318 }
319
320 }