blob: cf6876a54b1d79dd06fd60c2c1a5b9bc3fe9178c [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
37// This function just uses the PATH environment variable to find the program.
38Path
39Program::FindProgramByName(const std::string& progName) {
40
41 // Check some degenerate cases
42 if (progName.length() == 0) // no program
43 return Path();
44 Path temp;
45 if (!temp.set(progName)) // invalid name
46 return Path();
Benjamin Kramer9cd3dfe2009-07-28 22:08:15 +000047 // Use the given path verbatim if it contains any slashes; this matches
48 // the behavior of sh(1) and friends.
Dan Gohman33bff132009-07-28 23:25:18 +000049 if (progName.find('/') != std::string::npos)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000050 return temp;
51
Dan Gohman7e0ccf02009-08-05 17:32:39 +000052 // At this point, the file name does not contain slashes. Search for it
53 // through the directories specified in the PATH environment variable.
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +000054
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055 // Get the path. If its empty, we can't do anything to find it.
56 const char *PathStr = getenv("PATH");
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +000057 if (PathStr == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000058 return Path();
59
60 // Now we have a colon separated list of directories to search; try them.
Evan Cheng591bfc82008-05-05 18:30:58 +000061 size_t PathLen = strlen(PathStr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062 while (PathLen) {
63 // Find the first colon...
64 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
65
66 // Check to see if this first directory contains the executable...
67 Path FilePath;
68 if (FilePath.set(std::string(PathStr,Colon))) {
69 FilePath.appendComponent(progName);
70 if (FilePath.canExecute())
71 return FilePath; // Found the executable!
72 }
73
74 // Nope it wasn't in this directory, check the next path in the list!
75 PathLen -= Colon-PathStr;
76 PathStr = Colon;
77
78 // Advance past duplicate colons
79 while (*PathStr == ':') {
80 PathStr++;
81 PathLen--;
82 }
83 }
84 return Path();
85}
86
Matthijs Kooijman641150d2008-06-12 10:47:18 +000087static bool RedirectIO(const Path *Path, int FD, std::string* ErrMsg) {
88 if (Path == 0)
89 // Noop
90 return false;
91 std::string File;
92 if (Path->isEmpty())
93 // Redirect empty paths to /dev/null
94 File = "/dev/null";
95 else
Chris Lattnerb1aa85b2009-08-23 22:45:37 +000096 File = Path->str();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000097
98 // Open the file
99 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
100 if (InFD == -1) {
101 MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
Daniel Dunbarf7ea85d2009-04-20 20:50:13 +0000102 + (FD == 0 ? "input" : "output"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000103 return true;
104 }
105
106 // Install it as the requested FD
107 if (-1 == dup2(InFD, FD)) {
108 MakeErrMsg(ErrMsg, "Cannot dup2");
109 return true;
110 }
111 close(InFD); // Close the original FD
112 return false;
113}
114
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000115static void SetMemoryLimits (unsigned size)
116{
117#if HAVE_SYS_RESOURCE_H
118 struct rlimit r;
119 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
120
121 // Heap size
122 getrlimit (RLIMIT_DATA, &r);
123 r.rlim_cur = limit;
124 setrlimit (RLIMIT_DATA, &r);
125#ifdef RLIMIT_RSS
126 // Resident set size.
127 getrlimit (RLIMIT_RSS, &r);
128 r.rlim_cur = limit;
129 setrlimit (RLIMIT_RSS, &r);
130#endif
131#ifdef RLIMIT_AS // e.g. NetBSD doesn't have it.
132 // Virtual memory.
133 getrlimit (RLIMIT_AS, &r);
134 r.rlim_cur = limit;
135 setrlimit (RLIMIT_AS, &r);
136#endif
137#endif
138}
139
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000140bool
141Program::Execute(const Path& path,
142 const char** args,
143 const char** envp,
144 const Path** redirects,
145 unsigned memoryLimit,
146 std::string* ErrMsg)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000147{
148 if (!path.canExecute()) {
149 if (ErrMsg)
Chris Lattnerb1aa85b2009-08-23 22:45:37 +0000150 *ErrMsg = path.str() + " is not executable";
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000151 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000152 }
153
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000154 // Create a child process.
155 int child = fork();
156 switch (child) {
157 // An error occured: Return to the caller.
158 case -1:
159 MakeErrMsg(ErrMsg, "Couldn't fork");
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000160 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161
162 // Child process: Execute the program.
163 case 0: {
164 // Redirect file descriptors...
165 if (redirects) {
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000166 // Redirect stdin
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000167 if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000168 // Redirect stdout
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000169 if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +0000170 if (redirects[1] && redirects[2] &&
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000171 *(redirects[1]) == *(redirects[2])) {
172 // If stdout and stderr should go to the same place, redirect stderr
173 // to the FD already open for stdout.
174 if (-1 == dup2(1,2)) {
175 MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000176 return false;
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000177 }
178 } else {
179 // Just redirect stderr
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000180 if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181 }
182 }
183
184 // Set memory limits
185 if (memoryLimit!=0) {
186 SetMemoryLimits(memoryLimit);
187 }
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +0000188
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000189 // Execute!
190 if (envp != 0)
Daniel Dunbar1df47e82009-08-04 20:32:25 +0000191 execve(path.c_str(), (char**)args, (char**)envp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000192 else
Daniel Dunbar1df47e82009-08-04 20:32:25 +0000193 execv(path.c_str(), (char**)args);
Dan Gohmana629b692009-08-05 00:09:12 +0000194 // If the execve() failed, we should exit. Follow Unix protocol and
195 // return 127 if the executable was not found, and 126 otherwise.
196 // Use _exit rather than exit so that atexit functions and static
197 // object destructors cloned from the parent process aren't
198 // redundantly run, and so that any data buffered in stdio buffers
199 // cloned from the parent aren't redundantly written out.
200 _exit(errno == ENOENT ? 127 : 126);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000201 }
202
203 // Parent process: Break out of the switch to do our processing.
204 default:
205 break;
206 }
207
Mikhail Glushenkov50839532009-09-15 03:39:45 +0000208 Pid_ = child;
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000209
210 return true;
211}
212
213int
214Program::Wait(unsigned secondsToWait,
215 std::string* ErrMsg)
216{
217#ifdef HAVE_SYS_WAIT_H
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000218 struct sigaction Act, Old;
219
Mikhail Glushenkov50839532009-09-15 03:39:45 +0000220 if (Pid_ == 0) {
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000221 MakeErrMsg(ErrMsg, "Process not started!");
222 return -1;
223 }
224
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225 // Install a timeout handler.
226 if (secondsToWait) {
Duncan Sands104b3ff2009-09-07 05:58:25 +0000227 memset(&Act, 0, sizeof(Act));
228 Act.sa_handler = SIG_IGN;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000229 sigemptyset(&Act.sa_mask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230 sigaction(SIGALRM, &Act, &Old);
231 alarm(secondsToWait);
232 }
233
234 // Parent process: Wait for the child process to terminate.
235 int status;
Mikhail Glushenkov50839532009-09-15 03:39:45 +0000236 pid_t child = Pid_;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000237 while (wait(&status) != child)
238 if (secondsToWait && errno == EINTR) {
239 // Kill the child.
240 kill(child, SIGKILL);
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +0000241
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242 // Turn off the alarm and restore the signal handler
243 alarm(0);
244 sigaction(SIGALRM, &Old, 0);
245
246 // Wait for child to die
247 if (wait(&status) != child)
248 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
Devang Patel930a5ad2008-02-04 20:57:54 +0000249 else
250 MakeErrMsg(ErrMsg, "Child timed out", 0);
251
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252 return -1; // Timeout detected
Devang Patel930a5ad2008-02-04 20:57:54 +0000253 } else if (errno != EINTR) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254 MakeErrMsg(ErrMsg, "Error waiting for child process");
255 return -1;
256 }
257
258 // We exited normally without timeout, so turn off the timer.
259 if (secondsToWait) {
260 alarm(0);
261 sigaction(SIGALRM, &Old, 0);
262 }
263
264 // Return the proper exit status. 0=success, >0 is programs' exit status,
265 // <0 means a signal was returned, -9999999 means the program dumped core.
266 int result = 0;
267 if (WIFEXITED(status))
268 result = WEXITSTATUS(status);
269 else if (WIFSIGNALED(status))
270 result = 0 - WTERMSIG(status);
271#ifdef WCOREDUMP
272 else if (WCOREDUMP(status))
273 result |= 0x01000000;
274#endif
275 return result;
276#else
277 return -99;
278#endif
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +0000279
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000280}
281
Mikhail Glushenkova2801682009-09-08 19:50:27 +0000282bool
283Program::Kill(std::string* ErrMsg) {
Mikhail Glushenkov50839532009-09-15 03:39:45 +0000284 if (Pid_ == 0) {
Mikhail Glushenkova2801682009-09-08 19:50:27 +0000285 MakeErrMsg(ErrMsg, "Process not started!");
286 return true;
287 }
288
Mikhail Glushenkov50839532009-09-15 03:39:45 +0000289 if (kill(Pid_, SIGKILL) != 0) {
Mikhail Glushenkovfd1f9fe2009-09-09 09:51:47 +0000290 MakeErrMsg(ErrMsg, "The process couldn't be killed!");
291 return true;
292 }
293
294 return false;
Mikhail Glushenkova2801682009-09-08 19:50:27 +0000295}
296
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000297bool Program::ChangeStdinToBinary(){
298 // Do nothing, as Unix doesn't differentiate between text and binary.
299 return false;
300}
301
302bool Program::ChangeStdoutToBinary(){
303 // Do nothing, as Unix doesn't differentiate between text and binary.
304 return false;
305}
306
307}