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 // This function just uses the PATH environment variable to find the program.
39 Program::FindProgramByName(const std::string& progName) {
41 // Check some degenerate cases
42 if (progName.length() == 0) // no program
45 if (!temp.set(progName)) // invalid name
47 // Use the given path verbatim if it contains any slashes; this matches
48 // the behavior of sh(1) and friends.
49 if (progName.find('/') != std::string::npos)
52 // At this point, the file name does not contain slashes. Search for it
53 // through the directories specified in the PATH environment variable.
55 // Get the path. If its empty, we can't do anything to find it.
56 const char *PathStr = getenv("PATH");
60 // Now we have a colon separated list of directories to search; try them.
61 size_t PathLen = strlen(PathStr);
63 // Find the first colon...
64 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
66 // Check to see if this first directory contains the executable...
68 if (FilePath.set(std::string(PathStr,Colon))) {
69 FilePath.appendComponent(progName);
70 if (FilePath.canExecute())
71 return FilePath; // Found the executable!
74 // Nope it wasn't in this directory, check the next path in the list!
75 PathLen -= Colon-PathStr;
78 // Advance past duplicate colons
79 while (*PathStr == ':') {
87 static bool RedirectIO(const Path *Path, int FD, std::string* ErrMsg) {
93 // Redirect empty paths to /dev/null
99 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
101 MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
102 + (FD == 0 ? "input" : "output"));
106 // Install it as the requested FD
107 if (-1 == dup2(InFD, FD)) {
108 MakeErrMsg(ErrMsg, "Cannot dup2");
111 close(InFD); // Close the original FD
115 static void SetMemoryLimits (unsigned size)
117 #if HAVE_SYS_RESOURCE_H
119 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
122 getrlimit (RLIMIT_DATA, &r);
124 setrlimit (RLIMIT_DATA, &r);
126 // Resident set size.
127 getrlimit (RLIMIT_RSS, &r);
129 setrlimit (RLIMIT_RSS, &r);
131 #ifdef RLIMIT_AS // e.g. NetBSD doesn't have it.
133 getrlimit (RLIMIT_AS, &r);
135 setrlimit (RLIMIT_AS, &r);
141 Program::Execute(const Path& path,
144 const Path** redirects,
145 unsigned memoryLimit,
148 if (!path.canExecute()) {
150 *ErrMsg = path.str() + " is not executable";
154 // Create a child process.
157 // An error occured: Return to the caller.
159 MakeErrMsg(ErrMsg, "Couldn't fork");
162 // Child process: Execute the program.
164 // Redirect file descriptors...
167 if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
169 if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
170 if (redirects[1] && redirects[2] &&
171 *(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");
179 // Just redirect stderr
180 if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
185 if (memoryLimit!=0) {
186 SetMemoryLimits(memoryLimit);
191 execve(path.c_str(), (char**)args, (char**)envp);
193 execv(path.c_str(), (char**)args);
194 // 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);
203 // Parent process: Break out of the switch to do our processing.
214 Program::Wait(unsigned secondsToWait,
217 #ifdef HAVE_SYS_WAIT_H
218 struct sigaction Act, Old;
221 MakeErrMsg(ErrMsg, "Process not started!");
225 // Install a timeout handler.
227 memset(&Act, 0, sizeof(Act));
228 Act.sa_handler = SIG_IGN;
229 sigemptyset(&Act.sa_mask);
230 sigaction(SIGALRM, &Act, &Old);
231 alarm(secondsToWait);
234 // Parent process: Wait for the child process to terminate.
237 while (wait(&status) != child)
238 if (secondsToWait && errno == EINTR) {
240 kill(child, SIGKILL);
242 // Turn off the alarm and restore the signal handler
244 sigaction(SIGALRM, &Old, 0);
246 // Wait for child to die
247 if (wait(&status) != child)
248 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
250 MakeErrMsg(ErrMsg, "Child timed out", 0);
252 return -1; // Timeout detected
253 } else if (errno != EINTR) {
254 MakeErrMsg(ErrMsg, "Error waiting for child process");
258 // We exited normally without timeout, so turn off the timer.
261 sigaction(SIGALRM, &Old, 0);
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.
267 if (WIFEXITED(status))
268 result = WEXITSTATUS(status);
269 else if (WIFSIGNALED(status))
270 result = 0 - WTERMSIG(status);
272 else if (WCOREDUMP(status))
273 result |= 0x01000000;
283 Program::Kill(std::string* ErrMsg) {
285 MakeErrMsg(ErrMsg, "Process not started!");
289 if (kill(Pid_, SIGKILL) != 0) {
290 MakeErrMsg(ErrMsg, "The process couldn't be killed!");
297 bool Program::ChangeStdinToBinary(){
298 // Do nothing, as Unix doesn't differentiate between text and binary.
302 bool Program::ChangeStdoutToBinary(){
303 // Do nothing, as Unix doesn't differentiate between text and binary.