1 //===- llvm/System/Unix/Program.cpp -----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Reid Spencer and is distributed under the
6 // University of Illinois Open Source 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>
25 #if HAVE_SYS_RESOURCE_H
26 #include <sys/resource.h>
38 // This function just uses the PATH environment variable to find the program.
40 Program::FindProgramByName(const std::string& progName) {
42 // Check some degenerate cases
43 if (progName.length() == 0) // no program
46 if (!temp.set(progName)) // invalid name
48 // FIXME: have to check for absolute filename - we cannot assume anything
49 // about "." being in $PATH
50 if (temp.canExecute()) // already executable as is
53 // At this point, the file name is valid and its not executable
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 unsigned 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 RedirectFD(const std::string &File, int FD, std::string* ErrMsg) {
88 if (File.empty()) return false; // Noop
91 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
93 MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
94 + (FD == 0 ? "input" : "output") + "!\n");
98 // Install it as the requested FD
99 if (-1 == dup2(InFD, FD)) {
100 MakeErrMsg(ErrMsg, "Cannot dup2");
103 close(InFD); // Close the original FD
107 static bool Timeout = false;
108 static void TimeOutHandler(int Sig) {
112 static void SetMemoryLimits (unsigned size)
114 #if HAVE_SYS_RESOURCE_H
116 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
119 getrlimit (RLIMIT_DATA, &r);
121 setrlimit (RLIMIT_DATA, &r);
122 // Resident set size.
123 getrlimit (RLIMIT_RSS, &r);
125 setrlimit (RLIMIT_RSS, &r);
127 getrlimit (RLIMIT_AS, &r);
129 setrlimit (RLIMIT_AS, &r);
134 Program::ExecuteAndWait(const Path& path,
137 const Path** redirects,
138 unsigned secondsToWait,
139 unsigned memoryLimit,
142 if (!path.canExecute()) {
144 *ErrMsg = path.toString() + " is not executable";
148 #ifdef HAVE_SYS_WAIT_H
149 // Create a child process.
152 // An error occured: Return to the caller.
154 MakeErrMsg(ErrMsg, "Couldn't fork");
157 // Child process: Execute the program.
159 // Redirect file descriptors...
162 if (redirects[0]->isEmpty()) {
163 if (RedirectFD("/dev/null",0,ErrMsg)) { return -1; }
165 if (RedirectFD(redirects[0]->toString(), 0,ErrMsg)) { return -1; }
169 if (redirects[1]->isEmpty()) {
170 if (RedirectFD("/dev/null",1,ErrMsg)) { return -1; }
172 if (RedirectFD(redirects[1]->toString(),1,ErrMsg)) { return -1; }
175 if (redirects[1] && redirects[2] &&
176 *(redirects[1]) != *(redirects[2])) {
177 if (redirects[2]->isEmpty()) {
178 if (RedirectFD("/dev/null",2,ErrMsg)) { return -1; }
180 if (RedirectFD(redirects[2]->toString(), 2,ErrMsg)) { return -1; }
182 } else if (-1 == dup2(1,2)) {
183 MakeErrMsg(ErrMsg, "Can't redirect");
189 if (memoryLimit!=0) {
190 SetMemoryLimits(memoryLimit);
195 execve (path.c_str(), (char** const)args, (char**)envp);
197 execv (path.c_str(), (char** const)args);
198 // If the execve() failed, we should exit and let the parent pick up
199 // our non-zero exit status.
203 // Parent process: Break out of the switch to do our processing.
208 // Make sure stderr and stdout have been flushed
209 std::cerr << std::flush;
210 std::cout << std::flush;
214 struct sigaction Act, Old;
216 // Install a timeout handler.
219 Act.sa_sigaction = 0;
220 Act.sa_handler = TimeOutHandler;
221 sigemptyset(&Act.sa_mask);
223 sigaction(SIGALRM, &Act, &Old);
224 alarm(secondsToWait);
227 // Parent process: Wait for the child process to terminate.
229 while (wait(&status) != child)
230 if (secondsToWait && errno == EINTR) {
232 kill(child, SIGKILL);
234 // Turn off the alarm and restore the signal handler
236 sigaction(SIGALRM, &Old, 0);
238 // Wait for child to die
239 if (wait(&status) != child)
240 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
242 return -1; // Timeout detected
244 MakeErrMsg(ErrMsg, "Error waiting for child process");
248 // We exited normally without timeout, so turn off the timer.
251 sigaction(SIGALRM, &Old, 0);
254 // Return the proper exit status. 0=success, >0 is programs' exit status,
255 // <0 means a signal was returned, -9999999 means the program dumped core.
257 if (WIFEXITED(status))
258 result = WEXITSTATUS(status);
259 else if (WIFSIGNALED(status))
260 result = 0 - WTERMSIG(status);
262 else if (WCOREDUMP(status))
263 result |= 0x01000000;
272 bool Program::ChangeStdinToBinary(){
273 // Do nothing, as Unix doesn't differentiate between text and binary.
277 bool Program::ChangeStdoutToBinary(){
278 // Do nothing, as Unix doesn't differentiate between text and binary.