1 //===- llvm/System/Unix/Program.cpp -----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Unix specific portion of the Program class.
12 //===----------------------------------------------------------------------===//
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic UNIX code that
16 //=== is guaranteed to work on *all* UNIX variants.
17 //===----------------------------------------------------------------------===//
19 #include <llvm/Config/config.h>
24 #if HAVE_SYS_RESOURCE_H
25 #include <sys/resource.h>
37 Program::Program() : Data_(0) {}
39 Program::~Program() {}
41 unsigned Program::GetPid() const {
42 uint64_t pid = reinterpret_cast<uint64_t>(Data_);
43 return static_cast<unsigned>(pid);
46 // This function just uses the PATH environment variable to find the program.
48 Program::FindProgramByName(const std::string& progName) {
50 // Check some degenerate cases
51 if (progName.length() == 0) // no program
54 if (!temp.set(progName)) // invalid name
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)
61 // At this point, the file name does not contain slashes. Search for it
62 // through the directories specified in the PATH environment variable.
64 // Get the path. If its empty, we can't do anything to find it.
65 const char *PathStr = getenv("PATH");
69 // Now we have a colon separated list of directories to search; try them.
70 size_t PathLen = strlen(PathStr);
72 // Find the first colon...
73 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
75 // Check to see if this first directory contains the executable...
77 if (FilePath.set(std::string(PathStr,Colon))) {
78 FilePath.appendComponent(progName);
79 if (FilePath.canExecute())
80 return FilePath; // Found the executable!
83 // Nope it wasn't in this directory, check the next path in the list!
84 PathLen -= Colon-PathStr;
87 // Advance past duplicate colons
88 while (*PathStr == ':') {
96 static bool RedirectIO(const Path *Path, int FD, std::string* ErrMsg) {
102 // Redirect empty paths to /dev/null
108 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
110 MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
111 + (FD == 0 ? "input" : "output"));
115 // Install it as the requested FD
116 if (dup2(InFD, FD) == -1) {
117 MakeErrMsg(ErrMsg, "Cannot dup2");
121 close(InFD); // Close the original FD
125 static void TimeOutHandler(int Sig) {
128 static void SetMemoryLimits (unsigned size)
130 #if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
132 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
135 getrlimit (RLIMIT_DATA, &r);
137 setrlimit (RLIMIT_DATA, &r);
139 // Resident set size.
140 getrlimit (RLIMIT_RSS, &r);
142 setrlimit (RLIMIT_RSS, &r);
144 #ifdef RLIMIT_AS // e.g. NetBSD doesn't have it.
146 getrlimit (RLIMIT_AS, &r);
148 setrlimit (RLIMIT_AS, &r);
154 Program::Execute(const Path& path,
157 const Path** redirects,
158 unsigned memoryLimit,
161 if (!path.canExecute()) {
163 *ErrMsg = path.str() + " is not executable";
167 // Create a child process.
170 // An error occured: Return to the caller.
172 MakeErrMsg(ErrMsg, "Couldn't fork");
175 // Child process: Execute the program.
177 // Redirect file descriptors...
180 if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
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");
192 // Just redirect stderr
193 if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
198 if (memoryLimit!=0) {
199 SetMemoryLimits(memoryLimit);
204 execve(path.c_str(), (char**)args, (char**)envp);
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);
216 // Parent process: Break out of the switch to do our processing.
221 Data_ = reinterpret_cast<void*>(child);
227 Program::Wait(unsigned secondsToWait,
230 #ifdef HAVE_SYS_WAIT_H
231 struct sigaction Act, Old;
234 MakeErrMsg(ErrMsg, "Process not started!");
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.
242 Act.sa_sigaction = 0;
243 Act.sa_handler = TimeOutHandler;
244 sigemptyset(&Act.sa_mask);
246 sigaction(SIGALRM, &Act, &Old);
247 alarm(secondsToWait);
250 // Parent process: Wait for the child process to terminate.
252 uint64_t pid = reinterpret_cast<uint64_t>(Data_);
253 pid_t child = static_cast<pid_t>(pid);
254 while (waitpid(pid, &status, 0) != child)
255 if (secondsToWait && errno == EINTR) {
257 kill(child, SIGKILL);
259 // Turn off the alarm and restore the signal handler
261 sigaction(SIGALRM, &Old, 0);
263 // Wait for child to die
264 if (wait(&status) != child)
265 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
267 MakeErrMsg(ErrMsg, "Child timed out", 0);
269 return -1; // Timeout detected
270 } else if (errno != EINTR) {
271 MakeErrMsg(ErrMsg, "Error waiting for child process");
275 // We exited normally without timeout, so turn off the timer.
278 sigaction(SIGALRM, &Old, 0);
281 // Return the proper exit status. 0=success, >0 is programs' exit status,
282 // <0 means a signal was returned, -9999999 means the program dumped core.
284 if (WIFEXITED(status))
285 result = WEXITSTATUS(status);
286 else if (WIFSIGNALED(status))
287 result = 0 - WTERMSIG(status);
289 else if (WCOREDUMP(status))
290 result |= 0x01000000;
300 Program::Kill(std::string* ErrMsg) {
302 MakeErrMsg(ErrMsg, "Process not started!");
306 uint64_t pid64 = reinterpret_cast<uint64_t>(Data_);
307 pid_t pid = static_cast<pid_t>(pid64);
309 if (kill(pid, SIGKILL) != 0) {
310 MakeErrMsg(ErrMsg, "The process couldn't be killed!");
317 bool Program::ChangeStdinToBinary(){
318 // Do nothing, as Unix doesn't differentiate between text and binary.
322 bool Program::ChangeStdoutToBinary(){
323 // Do nothing, as Unix doesn't differentiate between text and binary.
327 bool Program::ChangeStderrToBinary(){
328 // Do nothing, as Unix doesn't differentiate between text and binary.