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);
123 // Resident set size.
124 getrlimit (RLIMIT_RSS, &r);
126 setrlimit (RLIMIT_RSS, &r);
129 getrlimit (RLIMIT_AS, &r);
131 setrlimit (RLIMIT_AS, &r);
136 Program::ExecuteAndWait(const Path& path,
139 const Path** redirects,
140 unsigned secondsToWait,
141 unsigned memoryLimit,
144 if (!path.canExecute()) {
146 *ErrMsg = path.toString() + " is not executable";
150 #ifdef HAVE_SYS_WAIT_H
151 // Create a child process.
154 // An error occured: Return to the caller.
156 MakeErrMsg(ErrMsg, "Couldn't fork");
159 // Child process: Execute the program.
161 // Redirect file descriptors...
164 if (redirects[0]->isEmpty()) {
165 if (RedirectFD("/dev/null",0,ErrMsg)) { return -1; }
167 if (RedirectFD(redirects[0]->toString(), 0,ErrMsg)) { return -1; }
171 if (redirects[1]->isEmpty()) {
172 if (RedirectFD("/dev/null",1,ErrMsg)) { return -1; }
174 if (RedirectFD(redirects[1]->toString(),1,ErrMsg)) { return -1; }
177 if (redirects[1] && redirects[2] &&
178 *(redirects[1]) != *(redirects[2])) {
179 if (redirects[2]->isEmpty()) {
180 if (RedirectFD("/dev/null",2,ErrMsg)) { return -1; }
182 if (RedirectFD(redirects[2]->toString(), 2,ErrMsg)) { return -1; }
184 } else if (-1 == dup2(1,2)) {
185 MakeErrMsg(ErrMsg, "Can't redirect");
191 if (memoryLimit!=0) {
192 SetMemoryLimits(memoryLimit);
197 execve (path.c_str(), (char** const)args, (char**)envp);
199 execv (path.c_str(), (char** const)args);
200 // If the execve() failed, we should exit and let the parent pick up
201 // our non-zero exit status.
205 // Parent process: Break out of the switch to do our processing.
210 // Make sure stderr and stdout have been flushed
211 std::cerr << std::flush;
212 std::cout << std::flush;
216 struct sigaction Act, Old;
218 // Install a timeout handler.
221 Act.sa_sigaction = 0;
222 Act.sa_handler = TimeOutHandler;
223 sigemptyset(&Act.sa_mask);
225 sigaction(SIGALRM, &Act, &Old);
226 alarm(secondsToWait);
229 // Parent process: Wait for the child process to terminate.
231 while (wait(&status) != child)
232 if (secondsToWait && errno == EINTR) {
234 kill(child, SIGKILL);
236 // Turn off the alarm and restore the signal handler
238 sigaction(SIGALRM, &Old, 0);
240 // Wait for child to die
241 if (wait(&status) != child)
242 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
244 return -1; // Timeout detected
246 MakeErrMsg(ErrMsg, "Error waiting for child process");
250 // We exited normally without timeout, so turn off the timer.
253 sigaction(SIGALRM, &Old, 0);
256 // Return the proper exit status. 0=success, >0 is programs' exit status,
257 // <0 means a signal was returned, -9999999 means the program dumped core.
259 if (WIFEXITED(status))
260 result = WEXITSTATUS(status);
261 else if (WIFSIGNALED(status))
262 result = 0 - WTERMSIG(status);
264 else if (WCOREDUMP(status))
265 result |= 0x01000000;
274 bool Program::ChangeStdinToBinary(){
275 // Do nothing, as Unix doesn't differentiate between text and binary.
279 bool Program::ChangeStdoutToBinary(){
280 // Do nothing, as Unix doesn't differentiate between text and binary.