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>
23 #ifdef HAVE_SYS_WAIT_H
28 extern char** environ;
33 // This function just uses the PATH environment variable to find the program.
35 Program::FindProgramByName(const std::string& progName) {
37 // Check some degenerate cases
38 if (progName.length() == 0) // no program
41 if (!temp.setFile(progName)) // invalid name
43 if (temp.executable()) // already executable as is
46 // At this point, the file name is valid and its not executable
48 // Get the path. If its empty, we can't do anything to find it.
49 const char *PathStr = getenv("PATH");
53 // Now we have a colon separated list of directories to search; try them.
54 unsigned PathLen = strlen(PathStr);
56 // Find the first colon...
57 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
59 // Check to see if this first directory contains the executable...
61 if (FilePath.setDirectory(std::string(PathStr,Colon))) {
62 FilePath.appendFile(progName);
63 if (FilePath.executable())
64 return FilePath; // Found the executable!
67 // Nope it wasn't in this directory, check the next path in the list!
68 PathLen -= Colon-PathStr;
71 // Advance past duplicate colons
72 while (*PathStr == ':') {
80 static void RedirectFD(const std::string &File, int FD) {
81 if (File.empty()) return; // Noop
84 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
86 ThrowErrno("Cannot open file '" + File + "' for "
87 + (FD == 0 ? "input" : "output") + "!\n");
90 dup2(InFD, FD); // Install it as the requested FD
91 close(InFD); // Close the original FD
94 static bool Timeout = false;
95 static void TimeOutHandler(int Sig) {
100 Program::ExecuteAndWait(const Path& path,
103 const Path** redirects,
104 unsigned secondsToWait
106 if (!path.executable())
107 throw path.toString() + " is not executable";
109 #ifdef HAVE_SYS_WAIT_H
110 // Create a child process.
113 // An error occured: Return to the caller.
115 ThrowErrno(std::string("Couldn't execute program '") + path.toString() +
119 // Child process: Execute the program.
121 // Redirect file descriptors...
124 if (redirects[0]->isEmpty())
125 RedirectFD("/dev/null",0);
127 RedirectFD(redirects[0]->toString(), 0);
129 if (redirects[1]->isEmpty())
130 RedirectFD("/dev/null",1);
132 RedirectFD(redirects[1]->toString(), 1);
133 if (redirects[1] && redirects[2] &&
134 *(redirects[1]) != *(redirects[2])) {
135 if (redirects[2]->isEmpty())
136 RedirectFD("/dev/null",2);
138 RedirectFD(redirects[2]->toString(), 2);
144 // Set up the environment
145 char** env = environ;
150 execve (path.c_str(), (char** const)args, env);
151 // If the execve() failed, we should exit and let the parent pick up
152 // our non-zero exit status.
156 // Parent process: Break out of the switch to do our processing.
161 // Make sure stderr and stdout have been flushed
162 std::cerr << std::flush;
163 std::cout << std::flush;
167 struct sigaction Act, Old;
169 // Install a timeout handler.
172 Act.sa_sigaction = 0;
173 Act.sa_handler = TimeOutHandler;
174 sigemptyset(&Act.sa_mask);
176 sigaction(SIGALRM, &Act, &Old);
177 alarm(secondsToWait);
180 // Parent process: Wait for the child process to terminate.
182 while (wait(&status) != child)
183 if (secondsToWait && errno == EINTR) {
185 kill(child, SIGKILL);
187 // Turn off the alarm and restore the signal handler
189 sigaction(SIGALRM, &Old, 0);
191 // Wait for child to die
192 if (wait(&status) != child)
193 ThrowErrno("Child timedout but wouldn't die");
195 return -1; // Timeout detected
197 ThrowErrno("Error waiting for child process");
200 // We exited normally without timeout, so turn off the timer.
203 sigaction(SIGALRM, &Old, 0);
206 // If the program exited normally with a zero exit status, return success!
207 if (WIFEXITED (status))
208 return WEXITSTATUS(status);
209 else if (WIFSIGNALED(status))
210 throw std::string("Program '") + path.toString() +
211 "' received terminating signal.";
215 "Program::ExecuteAndWait not implemented on this platform!\n");
221 // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab