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>
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);
128 #ifdef RLIMIT_AS // e.g. NetBSD doesn't have it.
130 getrlimit (RLIMIT_AS, &r);
132 setrlimit (RLIMIT_AS, &r);
138 Program::ExecuteAndWait(const Path& path,
141 const Path** redirects,
142 unsigned secondsToWait,
143 unsigned memoryLimit,
146 if (!path.canExecute()) {
148 *ErrMsg = path.toString() + " is not executable";
152 #ifdef HAVE_SYS_WAIT_H
153 // Create a child process.
156 // An error occured: Return to the caller.
158 MakeErrMsg(ErrMsg, "Couldn't fork");
161 // Child process: Execute the program.
163 // Redirect file descriptors...
166 if (redirects[0]->isEmpty()) {
167 if (RedirectFD("/dev/null",0,ErrMsg)) { return -1; }
169 if (RedirectFD(redirects[0]->toString(), 0,ErrMsg)) { return -1; }
173 if (redirects[1]->isEmpty()) {
174 if (RedirectFD("/dev/null",1,ErrMsg)) { return -1; }
176 if (RedirectFD(redirects[1]->toString(),1,ErrMsg)) { return -1; }
179 if (redirects[1] && redirects[2] &&
180 *(redirects[1]) != *(redirects[2])) {
181 if (redirects[2]->isEmpty()) {
182 if (RedirectFD("/dev/null",2,ErrMsg)) { return -1; }
184 if (RedirectFD(redirects[2]->toString(), 2,ErrMsg)) { return -1; }
186 } else if (-1 == dup2(1,2)) {
187 MakeErrMsg(ErrMsg, "Can't redirect");
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 and let the parent pick up
203 // our non-zero exit status.
207 // Parent process: Break out of the switch to do our processing.
212 // Make sure stderr and stdout have been flushed
213 std::cerr << std::flush;
214 std::cout << std::flush;
218 struct sigaction Act, Old;
220 // Install a timeout handler.
223 Act.sa_sigaction = 0;
224 Act.sa_handler = TimeOutHandler;
225 sigemptyset(&Act.sa_mask);
227 sigaction(SIGALRM, &Act, &Old);
228 alarm(secondsToWait);
231 // Parent process: Wait for the child process to terminate.
233 while (wait(&status) != child)
234 if (secondsToWait && errno == EINTR) {
236 kill(child, SIGKILL);
238 // Turn off the alarm and restore the signal handler
240 sigaction(SIGALRM, &Old, 0);
242 // Wait for child to die
243 if (wait(&status) != child)
244 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
246 MakeErrMsg(ErrMsg, "Child timed out", 0);
248 return -1; // Timeout detected
249 } else if (errno != EINTR) {
250 MakeErrMsg(ErrMsg, "Error waiting for child process");
254 // We exited normally without timeout, so turn off the timer.
257 sigaction(SIGALRM, &Old, 0);
260 // Return the proper exit status. 0=success, >0 is programs' exit status,
261 // <0 means a signal was returned, -9999999 means the program dumped core.
263 if (WIFEXITED(status))
264 result = WEXITSTATUS(status);
265 else if (WIFSIGNALED(status))
266 result = 0 - WTERMSIG(status);
268 else if (WCOREDUMP(status))
269 result |= 0x01000000;
278 bool Program::ChangeStdinToBinary(){
279 // Do nothing, as Unix doesn't differentiate between text and binary.
283 bool Program::ChangeStdoutToBinary(){
284 // Do nothing, as Unix doesn't differentiate between text and binary.