blob: adf7390f9fb2af2ed80648a480ab47c825296104 [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 Dunbar1b399062009-08-03 05:02:46 +000037Program::Program() : Pid_(0) {}
38
39Program::~Program() {}
40
Dan Gohmanf17a25c2007-07-18 16:29:46 +000041// This function just uses the PATH environment variable to find the program.
42Path
43Program::FindProgramByName(const std::string& progName) {
44
45 // Check some degenerate cases
46 if (progName.length() == 0) // no program
47 return Path();
48 Path temp;
49 if (!temp.set(progName)) // invalid name
50 return Path();
Benjamin Kramer9cd3dfe2009-07-28 22:08:15 +000051 // Use the given path verbatim if it contains any slashes; this matches
52 // the behavior of sh(1) and friends.
Dan Gohman33bff132009-07-28 23:25:18 +000053 if (progName.find('/') != std::string::npos)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000054 return temp;
55
Dan Gohman7e0ccf02009-08-05 17:32:39 +000056 // At this point, the file name does not contain slashes. Search for it
57 // through the directories specified in the PATH environment variable.
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +000058
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059 // Get the path. If its empty, we can't do anything to find it.
60 const char *PathStr = getenv("PATH");
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +000061 if (PathStr == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062 return Path();
63
64 // Now we have a colon separated list of directories to search; try them.
Evan Cheng591bfc82008-05-05 18:30:58 +000065 size_t PathLen = strlen(PathStr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000066 while (PathLen) {
67 // Find the first colon...
68 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
69
70 // Check to see if this first directory contains the executable...
71 Path FilePath;
72 if (FilePath.set(std::string(PathStr,Colon))) {
73 FilePath.appendComponent(progName);
74 if (FilePath.canExecute())
75 return FilePath; // Found the executable!
76 }
77
78 // Nope it wasn't in this directory, check the next path in the list!
79 PathLen -= Colon-PathStr;
80 PathStr = Colon;
81
82 // Advance past duplicate colons
83 while (*PathStr == ':') {
84 PathStr++;
85 PathLen--;
86 }
87 }
88 return Path();
89}
90
Matthijs Kooijman641150d2008-06-12 10:47:18 +000091static bool RedirectIO(const Path *Path, int FD, std::string* ErrMsg) {
92 if (Path == 0)
93 // Noop
94 return false;
95 std::string File;
96 if (Path->isEmpty())
97 // Redirect empty paths to /dev/null
98 File = "/dev/null";
99 else
Chris Lattnerb1aa85b2009-08-23 22:45:37 +0000100 File = Path->str();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000101
102 // Open the file
103 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
104 if (InFD == -1) {
105 MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
Daniel Dunbarf7ea85d2009-04-20 20:50:13 +0000106 + (FD == 0 ? "input" : "output"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107 return true;
108 }
109
110 // Install it as the requested FD
111 if (-1 == dup2(InFD, FD)) {
112 MakeErrMsg(ErrMsg, "Cannot dup2");
113 return true;
114 }
115 close(InFD); // Close the original FD
116 return false;
117}
118
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000119static void TimeOutHandler(int Sig) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000120}
121
122static void SetMemoryLimits (unsigned size)
123{
124#if HAVE_SYS_RESOURCE_H
125 struct rlimit r;
126 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
127
128 // Heap size
129 getrlimit (RLIMIT_DATA, &r);
130 r.rlim_cur = limit;
131 setrlimit (RLIMIT_DATA, &r);
132#ifdef RLIMIT_RSS
133 // Resident set size.
134 getrlimit (RLIMIT_RSS, &r);
135 r.rlim_cur = limit;
136 setrlimit (RLIMIT_RSS, &r);
137#endif
138#ifdef RLIMIT_AS // e.g. NetBSD doesn't have it.
139 // Virtual memory.
140 getrlimit (RLIMIT_AS, &r);
141 r.rlim_cur = limit;
142 setrlimit (RLIMIT_AS, &r);
143#endif
144#endif
145}
146
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000147bool
148Program::Execute(const Path& path,
149 const char** args,
150 const char** envp,
151 const Path** redirects,
152 unsigned memoryLimit,
153 std::string* ErrMsg)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000154{
155 if (!path.canExecute()) {
156 if (ErrMsg)
Chris Lattnerb1aa85b2009-08-23 22:45:37 +0000157 *ErrMsg = path.str() + " is not executable";
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000158 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000159 }
160
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161 // Create a child process.
162 int child = fork();
163 switch (child) {
164 // An error occured: Return to the caller.
165 case -1:
166 MakeErrMsg(ErrMsg, "Couldn't fork");
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000167 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000168
169 // Child process: Execute the program.
170 case 0: {
171 // Redirect file descriptors...
172 if (redirects) {
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000173 // Redirect stdin
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000174 if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000175 // Redirect stdout
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000176 if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +0000177 if (redirects[1] && redirects[2] &&
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000178 *(redirects[1]) == *(redirects[2])) {
179 // If stdout and stderr should go to the same place, redirect stderr
180 // to the FD already open for stdout.
181 if (-1 == dup2(1,2)) {
182 MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000183 return false;
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000184 }
185 } else {
186 // Just redirect stderr
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000187 if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188 }
189 }
190
191 // Set memory limits
192 if (memoryLimit!=0) {
193 SetMemoryLimits(memoryLimit);
194 }
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +0000195
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000196 // Execute!
197 if (envp != 0)
Daniel Dunbar1df47e82009-08-04 20:32:25 +0000198 execve(path.c_str(), (char**)args, (char**)envp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199 else
Daniel Dunbar1df47e82009-08-04 20:32:25 +0000200 execv(path.c_str(), (char**)args);
Dan Gohmana629b692009-08-05 00:09:12 +0000201 // If the execve() failed, we should exit. Follow Unix protocol and
202 // return 127 if the executable was not found, and 126 otherwise.
203 // Use _exit rather than exit so that atexit functions and static
204 // object destructors cloned from the parent process aren't
205 // redundantly run, and so that any data buffered in stdio buffers
206 // cloned from the parent aren't redundantly written out.
207 _exit(errno == ENOENT ? 127 : 126);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000208 }
209
210 // Parent process: Break out of the switch to do our processing.
211 default:
212 break;
213 }
214
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000215 Pid_ = child;
216
217 return true;
218}
219
220int
221Program::Wait(unsigned secondsToWait,
222 std::string* ErrMsg)
223{
224#ifdef HAVE_SYS_WAIT_H
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225 struct sigaction Act, Old;
226
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000227 if (Pid_ == 0) {
228 MakeErrMsg(ErrMsg, "Process not started!");
229 return -1;
230 }
231
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232 // Install a timeout handler.
233 if (secondsToWait) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000234 Act.sa_sigaction = 0;
235 Act.sa_handler = TimeOutHandler;
236 sigemptyset(&Act.sa_mask);
237 Act.sa_flags = 0;
238 sigaction(SIGALRM, &Act, &Old);
239 alarm(secondsToWait);
240 }
241
242 // Parent process: Wait for the child process to terminate.
243 int status;
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000244 int child = this->Pid_;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000245 while (wait(&status) != child)
246 if (secondsToWait && errno == EINTR) {
247 // Kill the child.
248 kill(child, SIGKILL);
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +0000249
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000250 // Turn off the alarm and restore the signal handler
251 alarm(0);
252 sigaction(SIGALRM, &Old, 0);
253
254 // Wait for child to die
255 if (wait(&status) != child)
256 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
Devang Patel930a5ad2008-02-04 20:57:54 +0000257 else
258 MakeErrMsg(ErrMsg, "Child timed out", 0);
259
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000260 return -1; // Timeout detected
Devang Patel930a5ad2008-02-04 20:57:54 +0000261 } else if (errno != EINTR) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262 MakeErrMsg(ErrMsg, "Error waiting for child process");
263 return -1;
264 }
265
266 // We exited normally without timeout, so turn off the timer.
267 if (secondsToWait) {
268 alarm(0);
269 sigaction(SIGALRM, &Old, 0);
270 }
271
272 // Return the proper exit status. 0=success, >0 is programs' exit status,
273 // <0 means a signal was returned, -9999999 means the program dumped core.
274 int result = 0;
275 if (WIFEXITED(status))
276 result = WEXITSTATUS(status);
277 else if (WIFSIGNALED(status))
278 result = 0 - WTERMSIG(status);
279#ifdef WCOREDUMP
280 else if (WCOREDUMP(status))
281 result |= 0x01000000;
282#endif
283 return result;
284#else
285 return -99;
286#endif
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +0000287
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288}
289
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290bool Program::ChangeStdinToBinary(){
291 // Do nothing, as Unix doesn't differentiate between text and binary.
292 return false;
293}
294
295bool Program::ChangeStdoutToBinary(){
296 // Do nothing, as Unix doesn't differentiate between text and binary.
297 return false;
298}
299
300}