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 return reinterpret_cast<unsigned>(Data_);
45 // This function just uses the PATH environment variable to find the program.
47 Program::FindProgramByName(const std::string& progName) {
49 // Check some degenerate cases
50 if (progName.length() == 0) // no program
53 if (!temp.set(progName)) // invalid name
55 // Use the given path verbatim if it contains any slashes; this matches
56 // the behavior of sh(1) and friends.
57 if (progName.find('/') != std::string::npos)
60 // At this point, the file name does not contain slashes. Search for it
61 // through the directories specified in the PATH environment variable.
63 // Get the path. If its empty, we can't do anything to find it.
64 const char *PathStr = getenv("PATH");
68 // Now we have a colon separated list of directories to search; try them.
69 size_t PathLen = strlen(PathStr);
71 // Find the first colon...
72 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
74 // Check to see if this first directory contains the executable...
76 if (FilePath.set(std::string(PathStr,Colon))) {
77 FilePath.appendComponent(progName);
78 if (FilePath.canExecute())
79 return FilePath; // Found the executable!
82 // Nope it wasn't in this directory, check the next path in the list!
83 PathLen -= Colon-PathStr;
86 // Advance past duplicate colons
87 while (*PathStr == ':') {
95 static bool RedirectIO(const Path *Path, int FD, std::string* ErrMsg) {
101 // Redirect empty paths to /dev/null
107 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
109 MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
110 + (FD == 0 ? "input" : "output"));
114 // Install it as the requested FD
115 if (-1 == dup2(InFD, FD)) {
116 MakeErrMsg(ErrMsg, "Cannot dup2");
119 close(InFD); // Close the original FD
123 static void SetMemoryLimits (unsigned size)
125 #if HAVE_SYS_RESOURCE_H
127 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
130 getrlimit (RLIMIT_DATA, &r);
132 setrlimit (RLIMIT_DATA, &r);
134 // Resident set size.
135 getrlimit (RLIMIT_RSS, &r);
137 setrlimit (RLIMIT_RSS, &r);
139 #ifdef RLIMIT_AS // e.g. NetBSD doesn't have it.
141 getrlimit (RLIMIT_AS, &r);
143 setrlimit (RLIMIT_AS, &r);
149 Program::Execute(const Path& path,
152 const Path** redirects,
153 unsigned memoryLimit,
156 if (!path.canExecute()) {
158 *ErrMsg = path.str() + " is not executable";
162 // Create a child process.
165 // An error occured: Return to the caller.
167 MakeErrMsg(ErrMsg, "Couldn't fork");
170 // Child process: Execute the program.
172 // Redirect file descriptors...
175 if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
177 if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
178 if (redirects[1] && redirects[2] &&
179 *(redirects[1]) == *(redirects[2])) {
180 // If stdout and stderr should go to the same place, redirect stderr
181 // to the FD already open for stdout.
182 if (-1 == dup2(1,2)) {
183 MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
187 // Just redirect stderr
188 if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
193 if (memoryLimit!=0) {
194 SetMemoryLimits(memoryLimit);
199 execve(path.c_str(), (char**)args, (char**)envp);
201 execv(path.c_str(), (char**)args);
202 // If the execve() failed, we should exit. Follow Unix protocol and
203 // return 127 if the executable was not found, and 126 otherwise.
204 // Use _exit rather than exit so that atexit functions and static
205 // object destructors cloned from the parent process aren't
206 // redundantly run, and so that any data buffered in stdio buffers
207 // cloned from the parent aren't redundantly written out.
208 _exit(errno == ENOENT ? 127 : 126);
211 // Parent process: Break out of the switch to do our processing.
216 Data_ = reinterpret_cast<void*>(child);
222 Program::Wait(unsigned secondsToWait,
225 #ifdef HAVE_SYS_WAIT_H
226 struct sigaction Act, Old;
229 MakeErrMsg(ErrMsg, "Process not started!");
233 // Install a timeout handler.
235 memset(&Act, 0, sizeof(Act));
236 Act.sa_handler = SIG_IGN;
237 sigemptyset(&Act.sa_mask);
238 sigaction(SIGALRM, &Act, &Old);
239 alarm(secondsToWait);
242 // Parent process: Wait for the child process to terminate.
244 pid_t child = reinterpret_cast<pid_t>(Data_);
245 while (wait(&status) != child)
246 if (secondsToWait && errno == EINTR) {
248 kill(child, SIGKILL);
250 // Turn off the alarm and restore the signal handler
252 sigaction(SIGALRM, &Old, 0);
254 // Wait for child to die
255 if (wait(&status) != child)
256 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
258 MakeErrMsg(ErrMsg, "Child timed out", 0);
260 return -1; // Timeout detected
261 } else if (errno != EINTR) {
262 MakeErrMsg(ErrMsg, "Error waiting for child process");
266 // We exited normally without timeout, so turn off the timer.
269 sigaction(SIGALRM, &Old, 0);
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.
275 if (WIFEXITED(status))
276 result = WEXITSTATUS(status);
277 else if (WIFSIGNALED(status))
278 result = 0 - WTERMSIG(status);
280 else if (WCOREDUMP(status))
281 result |= 0x01000000;
291 Program::Kill(std::string* ErrMsg) {
293 MakeErrMsg(ErrMsg, "Process not started!");
297 pid_t pid = reinterpret_cast<pid_t>(Data_);
298 return (kill(pid, SIGKILL) == 0);
301 bool Program::ChangeStdinToBinary(){
302 // Do nothing, as Unix doesn't differentiate between text and binary.
306 bool Program::ChangeStdoutToBinary(){
307 // Do nothing, as Unix doesn't differentiate between text and binary.