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>
35 // This function just uses the PATH environment variable to find the program.
37 Program::FindProgramByName(const std::string& progName) {
39 // Check some degenerate cases
40 if (progName.length() == 0) // no program
43 if (!temp.set(progName)) // invalid name
45 // FIXME: have to check for absolute filename - we cannot assume anything
46 // about "." being in $PATH
47 if (temp.canExecute()) // already executable as is
50 // At this point, the file name is valid and its not executable
52 // Get the path. If its empty, we can't do anything to find it.
53 const char *PathStr = getenv("PATH");
57 // Now we have a colon separated list of directories to search; try them.
58 unsigned PathLen = strlen(PathStr);
60 // Find the first colon...
61 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
63 // Check to see if this first directory contains the executable...
65 if (FilePath.set(std::string(PathStr,Colon))) {
66 FilePath.appendComponent(progName);
67 if (FilePath.canExecute())
68 return FilePath; // Found the executable!
71 // Nope it wasn't in this directory, check the next path in the list!
72 PathLen -= Colon-PathStr;
75 // Advance past duplicate colons
76 while (*PathStr == ':') {
84 static void RedirectFD(const std::string &File, int FD) {
85 if (File.empty()) return; // Noop
88 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
90 ThrowErrno("Cannot open file '" + File + "' for "
91 + (FD == 0 ? "input" : "output") + "!\n");
94 dup2(InFD, FD); // Install it as the requested FD
95 close(InFD); // Close the original FD
98 static bool Timeout = false;
99 static void TimeOutHandler(int Sig) {
104 Program::ExecuteAndWait(const Path& path,
107 const Path** redirects,
108 unsigned secondsToWait
110 if (!path.canExecute())
111 throw path.toString() + " is not executable";
113 #ifdef HAVE_SYS_WAIT_H
114 // Create a child process.
117 // An error occured: Return to the caller.
119 ThrowErrno(std::string("Couldn't execute program '") + path.toString() +
123 // Child process: Execute the program.
125 // Redirect file descriptors...
128 if (redirects[0]->isEmpty())
129 RedirectFD("/dev/null",0);
131 RedirectFD(redirects[0]->toString(), 0);
133 if (redirects[1]->isEmpty())
134 RedirectFD("/dev/null",1);
136 RedirectFD(redirects[1]->toString(), 1);
137 if (redirects[1] && redirects[2] &&
138 *(redirects[1]) != *(redirects[2])) {
139 if (redirects[2]->isEmpty())
140 RedirectFD("/dev/null",2);
142 RedirectFD(redirects[2]->toString(), 2);
150 execve (path.c_str(), (char** const)args, (char**)envp);
152 execv (path.c_str(), (char** const)args);
153 // If the execve() failed, we should exit and let the parent pick up
154 // our non-zero exit status.
158 // Parent process: Break out of the switch to do our processing.
163 // Make sure stderr and stdout have been flushed
164 std::cerr << std::flush;
165 std::cout << std::flush;
169 struct sigaction Act, Old;
171 // Install a timeout handler.
174 Act.sa_sigaction = 0;
175 Act.sa_handler = TimeOutHandler;
176 sigemptyset(&Act.sa_mask);
178 sigaction(SIGALRM, &Act, &Old);
179 alarm(secondsToWait);
182 // Parent process: Wait for the child process to terminate.
184 while (wait(&status) != child)
185 if (secondsToWait && errno == EINTR) {
187 kill(child, SIGKILL);
189 // Turn off the alarm and restore the signal handler
191 sigaction(SIGALRM, &Old, 0);
193 // Wait for child to die
194 if (wait(&status) != child)
195 ThrowErrno("Child timedout but wouldn't die");
197 return -1; // Timeout detected
199 ThrowErrno("Error waiting for child process");
202 // We exited normally without timeout, so turn off the timer.
205 sigaction(SIGALRM, &Old, 0);
208 // Return the proper exit status. 0=success, >0 is programs' exit status,
209 // <0 means a signal was returned, -9999999 means the program dumped core.
211 if (WIFEXITED(status))
212 result = WEXITSTATUS(status);
213 else if (WIFSIGNALED(status))
214 result = 0 - WTERMSIG(status);
216 else if (WCOREDUMP(status))
217 result |= 0x01000000;
226 void Program::ChangeStdinToBinary(){
227 // Do nothing, as Unix doesn't differentiate between text and binary.
230 void Program::ChangeStdoutToBinary(){
231 // Do nothing, as Unix doesn't differentiate between text and binary.