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") + "!\n");
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...
173 if (RedirectIO(redirects[0], 0, ErrMsg)) { return -1; }
174 if (RedirectIO(redirects[1], 1, ErrMsg)) { return -1; }
175 if (redirects[1] && redirects[2] &&
176 *(redirects[1]) != *(redirects[2])) {
177 if (RedirectIO(redirects[2], 2, ErrMsg)) { return -1; }
178 } else if (-1 == dup2(1,2)) {
179 MakeErrMsg(ErrMsg, "Can't redirect");
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 and let the parent pick up
195 // our non-zero exit status.
199 // Parent process: Break out of the switch to do our processing.
204 // Make sure stderr and stdout have been flushed
205 std::cerr << std::flush;
206 std::cout << std::flush;
210 struct sigaction Act, Old;
212 // Install a timeout handler.
215 Act.sa_sigaction = 0;
216 Act.sa_handler = TimeOutHandler;
217 sigemptyset(&Act.sa_mask);
219 sigaction(SIGALRM, &Act, &Old);
220 alarm(secondsToWait);
223 // Parent process: Wait for the child process to terminate.
225 while (wait(&status) != child)
226 if (secondsToWait && errno == EINTR) {
228 kill(child, SIGKILL);
230 // Turn off the alarm and restore the signal handler
232 sigaction(SIGALRM, &Old, 0);
234 // Wait for child to die
235 if (wait(&status) != child)
236 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
238 MakeErrMsg(ErrMsg, "Child timed out", 0);
240 return -1; // Timeout detected
241 } else if (errno != EINTR) {
242 MakeErrMsg(ErrMsg, "Error waiting for child process");
246 // We exited normally without timeout, so turn off the timer.
249 sigaction(SIGALRM, &Old, 0);
252 // Return the proper exit status. 0=success, >0 is programs' exit status,
253 // <0 means a signal was returned, -9999999 means the program dumped core.
255 if (WIFEXITED(status))
256 result = WEXITSTATUS(status);
257 else if (WIFSIGNALED(status))
258 result = 0 - WTERMSIG(status);
260 else if (WCOREDUMP(status))
261 result |= 0x01000000;
270 bool Program::ChangeStdinToBinary(){
271 // Do nothing, as Unix doesn't differentiate between text and binary.
275 bool Program::ChangeStdoutToBinary(){
276 // Do nothing, as Unix doesn't differentiate between text and binary.