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() : Pid_(0) {}
39 Program::~Program() {}
41 // This function just uses the PATH environment variable to find the program.
43 Program::FindProgramByName(const std::string& progName) {
45 // Check some degenerate cases
46 if (progName.length() == 0) // no program
49 if (!temp.set(progName)) // invalid name
51 // Use the given path verbatim if it contains any slashes; this matches
52 // the behavior of sh(1) and friends.
53 if (progName.find('/') != std::string::npos)
56 // At this point, the file name does not contain slashes. Search for it
57 // through the directories specified in the PATH environment variable.
59 // Get the path. If its empty, we can't do anything to find it.
60 const char *PathStr = getenv("PATH");
64 // Now we have a colon separated list of directories to search; try them.
65 size_t PathLen = strlen(PathStr);
67 // Find the first colon...
68 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
70 // Check to see if this first directory contains the executable...
72 if (FilePath.set(std::string(PathStr,Colon))) {
73 FilePath.appendComponent(progName);
74 if (FilePath.canExecute())
75 return FilePath; // Found the executable!
78 // Nope it wasn't in this directory, check the next path in the list!
79 PathLen -= Colon-PathStr;
82 // Advance past duplicate colons
83 while (*PathStr == ':') {
91 static bool RedirectIO(const Path *Path, int FD, std::string* ErrMsg) {
97 // Redirect empty paths to /dev/null
103 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
105 MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
106 + (FD == 0 ? "input" : "output"));
110 // Install it as the requested FD
111 if (-1 == dup2(InFD, FD)) {
112 MakeErrMsg(ErrMsg, "Cannot dup2");
115 close(InFD); // Close the original FD
119 static bool Timeout = false;
120 static void TimeOutHandler(int Sig) {
124 static void SetMemoryLimits (unsigned size)
126 #if HAVE_SYS_RESOURCE_H
128 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
131 getrlimit (RLIMIT_DATA, &r);
133 setrlimit (RLIMIT_DATA, &r);
135 // Resident set size.
136 getrlimit (RLIMIT_RSS, &r);
138 setrlimit (RLIMIT_RSS, &r);
140 #ifdef RLIMIT_AS // e.g. NetBSD doesn't have it.
142 getrlimit (RLIMIT_AS, &r);
144 setrlimit (RLIMIT_AS, &r);
150 Program::Execute(const Path& path,
153 const Path** redirects,
154 unsigned memoryLimit,
157 if (!path.canExecute()) {
159 *ErrMsg = path.str() + " is not executable";
163 // Create a child process.
166 // An error occured: Return to the caller.
168 MakeErrMsg(ErrMsg, "Couldn't fork");
171 // Child process: Execute the program.
173 // Redirect file descriptors...
176 if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
178 if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
179 if (redirects[1] && redirects[2] &&
180 *(redirects[1]) == *(redirects[2])) {
181 // If stdout and stderr should go to the same place, redirect stderr
182 // to the FD already open for stdout.
183 if (-1 == dup2(1,2)) {
184 MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
188 // Just redirect stderr
189 if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
194 if (memoryLimit!=0) {
195 SetMemoryLimits(memoryLimit);
200 execve(path.c_str(), (char**)args, (char**)envp);
202 execv(path.c_str(), (char**)args);
203 // If the execve() failed, we should exit. Follow Unix protocol and
204 // return 127 if the executable was not found, and 126 otherwise.
205 // Use _exit rather than exit so that atexit functions and static
206 // object destructors cloned from the parent process aren't
207 // redundantly run, and so that any data buffered in stdio buffers
208 // cloned from the parent aren't redundantly written out.
209 _exit(errno == ENOENT ? 127 : 126);
212 // Parent process: Break out of the switch to do our processing.
223 Program::Wait(unsigned secondsToWait,
226 #ifdef HAVE_SYS_WAIT_H
227 struct sigaction Act, Old;
230 MakeErrMsg(ErrMsg, "Process not started!");
234 // Install a timeout handler.
237 Act.sa_sigaction = 0;
238 Act.sa_handler = TimeOutHandler;
239 sigemptyset(&Act.sa_mask);
241 sigaction(SIGALRM, &Act, &Old);
242 alarm(secondsToWait);
245 // Parent process: Wait for the child process to terminate.
247 int child = this->Pid_;
248 while (wait(&status) != child)
249 if (secondsToWait && errno == EINTR) {
251 kill(child, SIGKILL);
253 // Turn off the alarm and restore the signal handler
255 sigaction(SIGALRM, &Old, 0);
257 // Wait for child to die
258 if (wait(&status) != child)
259 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
261 MakeErrMsg(ErrMsg, "Child timed out", 0);
263 return -1; // Timeout detected
264 } else if (errno != EINTR) {
265 MakeErrMsg(ErrMsg, "Error waiting for child process");
269 // We exited normally without timeout, so turn off the timer.
272 sigaction(SIGALRM, &Old, 0);
275 // Return the proper exit status. 0=success, >0 is programs' exit status,
276 // <0 means a signal was returned, -9999999 means the program dumped core.
278 if (WIFEXITED(status))
279 result = WEXITSTATUS(status);
280 else if (WIFSIGNALED(status))
281 result = 0 - WTERMSIG(status);
283 else if (WCOREDUMP(status))
284 result |= 0x01000000;
293 bool Program::ChangeStdinToBinary(){
294 // Do nothing, as Unix doesn't differentiate between text and binary.
298 bool Program::ChangeStdoutToBinary(){
299 // Do nothing, as Unix doesn't differentiate between text and binary.