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 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
96 File = Path->toString();
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 bool Timeout = false;
116 static void TimeOutHandler(int Sig) {
120 static void SetMemoryLimits (unsigned size)
122 #if HAVE_SYS_RESOURCE_H
124 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
127 getrlimit (RLIMIT_DATA, &r);
129 setrlimit (RLIMIT_DATA, &r);
131 // Resident set size.
132 getrlimit (RLIMIT_RSS, &r);
134 setrlimit (RLIMIT_RSS, &r);
136 #ifdef RLIMIT_AS // e.g. NetBSD doesn't have it.
138 getrlimit (RLIMIT_AS, &r);
140 setrlimit (RLIMIT_AS, &r);
146 Program::ExecuteAndWait(const Path& path,
149 const Path** redirects,
150 unsigned secondsToWait,
151 unsigned memoryLimit,
154 if (!path.canExecute()) {
156 *ErrMsg = path.toString() + " is not executable";
160 #ifdef HAVE_SYS_WAIT_H
161 // Create a child process.
164 // An error occured: Return to the caller.
166 MakeErrMsg(ErrMsg, "Couldn't fork");
169 // Child process: Execute the program.
171 // Redirect file descriptors...
174 if (RedirectIO(redirects[0], 0, ErrMsg)) { return -1; }
176 if (RedirectIO(redirects[1], 1, ErrMsg)) { return -1; }
177 if (redirects[1] && redirects[2] &&
178 *(redirects[1]) == *(redirects[2])) {
179 // If stdout and stderr should go to the same place, redirect stderr
180 // to the FD already open for stdout.
181 if (-1 == dup2(1,2)) {
182 MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
186 // Just redirect stderr
187 if (RedirectIO(redirects[2], 2, ErrMsg)) { return -1; }
192 if (memoryLimit!=0) {
193 SetMemoryLimits(memoryLimit);
198 execve (path.c_str(), (char**)args, (char**)envp);
200 execv (path.c_str(), (char**)args);
201 // If the execve() failed, we should exit and let the parent pick up
202 // our non-zero exit status.
206 // Parent process: Break out of the switch to do our processing.
211 // Make sure stderr and stdout have been flushed
212 std::cerr << std::flush;
213 std::cout << std::flush;
217 struct sigaction Act, Old;
219 // Install a timeout handler.
222 Act.sa_sigaction = 0;
223 Act.sa_handler = TimeOutHandler;
224 sigemptyset(&Act.sa_mask);
226 sigaction(SIGALRM, &Act, &Old);
227 alarm(secondsToWait);
230 // Parent process: Wait for the child process to terminate.
232 while (wait(&status) != child)
233 if (secondsToWait && errno == EINTR) {
235 kill(child, SIGKILL);
237 // Turn off the alarm and restore the signal handler
239 sigaction(SIGALRM, &Old, 0);
241 // Wait for child to die
242 if (wait(&status) != child)
243 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
245 MakeErrMsg(ErrMsg, "Child timed out", 0);
247 return -1; // Timeout detected
248 } else if (errno != EINTR) {
249 MakeErrMsg(ErrMsg, "Error waiting for child process");
253 // We exited normally without timeout, so turn off the timer.
256 sigaction(SIGALRM, &Old, 0);
259 // Return the proper exit status. 0=success, >0 is programs' exit status,
260 // <0 means a signal was returned, -9999999 means the program dumped core.
262 if (WIFEXITED(status))
263 result = WEXITSTATUS(status);
264 else if (WIFSIGNALED(status))
265 result = 0 - WTERMSIG(status);
267 else if (WCOREDUMP(status))
268 result |= 0x01000000;
277 bool Program::ChangeStdinToBinary(){
278 // Do nothing, as Unix doesn't differentiate between text and binary.
282 bool Program::ChangeStdoutToBinary(){
283 // Do nothing, as Unix doesn't differentiate between text and binary.