blob: c10498a375ac812e465bfc69828c0f9a52d4ca17 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- llvm/System/Unix/Program.cpp -----------------------------*- C++ -*-===//
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +00002//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +00007//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008//===----------------------------------------------------------------------===//
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"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000021#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
34namespace llvm {
35using namespace sys;
36
Daniel Dunbar0dfef162009-09-22 04:44:56 +000037Program::Program() : Data_(0) {}
38
39Program::~Program() {}
40
41unsigned Program::GetPid() const {
42 uint64_t pid = reinterpret_cast<uint64_t>(Data_);
43 return static_cast<unsigned>(pid);
44}
45
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046// This function just uses the PATH environment variable to find the program.
47Path
48Program::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();
Benjamin Kramer9cd3dfe2009-07-28 22:08:15 +000056 // Use the given path verbatim if it contains any slashes; this matches
57 // the behavior of sh(1) and friends.
Dan Gohman33bff132009-07-28 23:25:18 +000058 if (progName.find('/') != std::string::npos)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059 return temp;
60
Dan Gohman7e0ccf02009-08-05 17:32:39 +000061 // At this point, the file name does not contain slashes. Search for it
62 // through the directories specified in the PATH environment variable.
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +000063
Dan Gohmanf17a25c2007-07-18 16:29:46 +000064 // Get the path. If its empty, we can't do anything to find it.
65 const char *PathStr = getenv("PATH");
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +000066 if (PathStr == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000067 return Path();
68
69 // Now we have a colon separated list of directories to search; try them.
Evan Cheng591bfc82008-05-05 18:30:58 +000070 size_t PathLen = strlen(PathStr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000071 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
Matthijs Kooijman641150d2008-06-12 10:47:18 +000096static 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
Chris Lattnerb1aa85b2009-08-23 22:45:37 +0000105 File = Path->str();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000106
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 "
Daniel Dunbarf7ea85d2009-04-20 20:50:13 +0000111 + (FD == 0 ? "input" : "output"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000112 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
Duncan Sands5987b822009-11-08 20:55:48 +0000124static void TimeOutHandler(int Sig) {
125}
126
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127static void SetMemoryLimits (unsigned size)
128{
Chris Lattner2f932e32010-02-12 00:37:46 +0000129#if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000130 struct rlimit r;
131 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
132
133 // Heap size
134 getrlimit (RLIMIT_DATA, &r);
135 r.rlim_cur = limit;
136 setrlimit (RLIMIT_DATA, &r);
137#ifdef RLIMIT_RSS
138 // Resident set size.
139 getrlimit (RLIMIT_RSS, &r);
140 r.rlim_cur = limit;
141 setrlimit (RLIMIT_RSS, &r);
142#endif
143#ifdef RLIMIT_AS // e.g. NetBSD doesn't have it.
144 // Virtual memory.
145 getrlimit (RLIMIT_AS, &r);
146 r.rlim_cur = limit;
147 setrlimit (RLIMIT_AS, &r);
148#endif
149#endif
150}
151
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000152bool
153Program::Execute(const Path& path,
154 const char** args,
155 const char** envp,
156 const Path** redirects,
157 unsigned memoryLimit,
158 std::string* ErrMsg)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000159{
160 if (!path.canExecute()) {
161 if (ErrMsg)
Chris Lattnerb1aa85b2009-08-23 22:45:37 +0000162 *ErrMsg = path.str() + " is not executable";
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000163 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000164 }
165
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000166 // Create a child process.
167 int child = fork();
168 switch (child) {
169 // An error occured: Return to the caller.
170 case -1:
171 MakeErrMsg(ErrMsg, "Couldn't fork");
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000172 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000173
174 // Child process: Execute the program.
175 case 0: {
176 // Redirect file descriptors...
177 if (redirects) {
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000178 // Redirect stdin
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000179 if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000180 // Redirect stdout
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000181 if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +0000182 if (redirects[1] && redirects[2] &&
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000183 *(redirects[1]) == *(redirects[2])) {
184 // If stdout and stderr should go to the same place, redirect stderr
185 // to the FD already open for stdout.
186 if (-1 == dup2(1,2)) {
187 MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000188 return false;
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000189 }
190 } else {
191 // Just redirect stderr
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000192 if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193 }
194 }
195
196 // Set memory limits
197 if (memoryLimit!=0) {
198 SetMemoryLimits(memoryLimit);
199 }
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +0000200
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000201 // Execute!
202 if (envp != 0)
Daniel Dunbar1df47e82009-08-04 20:32:25 +0000203 execve(path.c_str(), (char**)args, (char**)envp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000204 else
Daniel Dunbar1df47e82009-08-04 20:32:25 +0000205 execv(path.c_str(), (char**)args);
Dan Gohmana629b692009-08-05 00:09:12 +0000206 // If the execve() failed, we should exit. Follow Unix protocol and
207 // return 127 if the executable was not found, and 126 otherwise.
208 // Use _exit rather than exit so that atexit functions and static
209 // object destructors cloned from the parent process aren't
210 // redundantly run, and so that any data buffered in stdio buffers
211 // cloned from the parent aren't redundantly written out.
212 _exit(errno == ENOENT ? 127 : 126);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000213 }
214
215 // Parent process: Break out of the switch to do our processing.
216 default:
217 break;
218 }
219
Daniel Dunbar0dfef162009-09-22 04:44:56 +0000220 Data_ = reinterpret_cast<void*>(child);
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000221
222 return true;
223}
224
225int
226Program::Wait(unsigned secondsToWait,
227 std::string* ErrMsg)
228{
229#ifdef HAVE_SYS_WAIT_H
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230 struct sigaction Act, Old;
231
Daniel Dunbar0dfef162009-09-22 04:44:56 +0000232 if (Data_ == 0) {
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000233 MakeErrMsg(ErrMsg, "Process not started!");
234 return -1;
235 }
236
Duncan Sands5987b822009-11-08 20:55:48 +0000237 // Install a timeout handler. The handler itself does nothing, but the simple
238 // fact of having a handler at all causes the wait below to return with EINTR,
239 // unlike if we used SIG_IGN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000240 if (secondsToWait) {
Duncan Sands5987b822009-11-08 20:55:48 +0000241 Act.sa_sigaction = 0;
242 Act.sa_handler = TimeOutHandler;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000243 sigemptyset(&Act.sa_mask);
Duncan Sands5987b822009-11-08 20:55:48 +0000244 Act.sa_flags = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000245 sigaction(SIGALRM, &Act, &Old);
246 alarm(secondsToWait);
247 }
248
249 // Parent process: Wait for the child process to terminate.
250 int status;
Daniel Dunbar0dfef162009-09-22 04:44:56 +0000251 uint64_t pid = reinterpret_cast<uint64_t>(Data_);
252 pid_t child = static_cast<pid_t>(pid);
Ted Kremenekb2bdf612009-10-22 22:16:17 +0000253 while (waitpid(pid, &status, 0) != child)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254 if (secondsToWait && errno == EINTR) {
255 // Kill the child.
256 kill(child, SIGKILL);
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +0000257
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000258 // Turn off the alarm and restore the signal handler
259 alarm(0);
260 sigaction(SIGALRM, &Old, 0);
261
262 // Wait for child to die
263 if (wait(&status) != child)
264 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
Devang Patel930a5ad2008-02-04 20:57:54 +0000265 else
266 MakeErrMsg(ErrMsg, "Child timed out", 0);
267
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000268 return -1; // Timeout detected
Devang Patel930a5ad2008-02-04 20:57:54 +0000269 } else if (errno != EINTR) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000270 MakeErrMsg(ErrMsg, "Error waiting for child process");
271 return -1;
272 }
273
274 // We exited normally without timeout, so turn off the timer.
275 if (secondsToWait) {
276 alarm(0);
277 sigaction(SIGALRM, &Old, 0);
278 }
279
280 // Return the proper exit status. 0=success, >0 is programs' exit status,
281 // <0 means a signal was returned, -9999999 means the program dumped core.
282 int result = 0;
283 if (WIFEXITED(status))
284 result = WEXITSTATUS(status);
285 else if (WIFSIGNALED(status))
286 result = 0 - WTERMSIG(status);
287#ifdef WCOREDUMP
288 else if (WCOREDUMP(status))
289 result |= 0x01000000;
290#endif
291 return result;
292#else
293 return -99;
294#endif
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +0000295
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000296}
297
Mikhail Glushenkova2801682009-09-08 19:50:27 +0000298bool
299Program::Kill(std::string* ErrMsg) {
Daniel Dunbar0dfef162009-09-22 04:44:56 +0000300 if (Data_ == 0) {
Mikhail Glushenkova2801682009-09-08 19:50:27 +0000301 MakeErrMsg(ErrMsg, "Process not started!");
302 return true;
303 }
304
Daniel Dunbar0dfef162009-09-22 04:44:56 +0000305 uint64_t pid64 = reinterpret_cast<uint64_t>(Data_);
306 pid_t pid = static_cast<pid_t>(pid64);
307
308 if (kill(pid, SIGKILL) != 0) {
Mikhail Glushenkovfd1f9fe2009-09-09 09:51:47 +0000309 MakeErrMsg(ErrMsg, "The process couldn't be killed!");
310 return true;
311 }
312
313 return false;
Mikhail Glushenkova2801682009-09-08 19:50:27 +0000314}
315
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316bool Program::ChangeStdinToBinary(){
317 // Do nothing, as Unix doesn't differentiate between text and binary.
318 return false;
319}
320
321bool Program::ChangeStdoutToBinary(){
322 // Do nothing, as Unix doesn't differentiate between text and binary.
323 return false;
324}
325
Douglas Gregore0919aa2010-01-28 06:42:08 +0000326bool Program::ChangeStderrToBinary(){
327 // Do nothing, as Unix doesn't differentiate between text and binary.
328 return false;
329}
330
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331}