Use <> for system #include files
[oota-llvm.git] / lib / System / Unix / Program.inc
1 //===- llvm/System/Unix/Program.cpp -----------------------------*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Unix specific portion of the Program class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic UNIX code that
16 //===          is guaranteed to work on *all* UNIX variants.
17 //===----------------------------------------------------------------------===//
18
19 #include <llvm/Config/config.h>
20 #include "Unix.h"
21 #include <sys/stat.h>
22 #include <signal.h>
23 #include <fcntl.h>
24 #ifdef HAVE_SYS_WAIT_H
25 #include <sys/wait.h>
26 #endif
27 #include <iostream>
28
29 extern char** environ;
30
31 namespace llvm {
32 using namespace sys;
33
34 // This function just uses the PATH environment variable to find the program.
35 Path
36 Program::FindProgramByName(const std::string& progName) {
37
38   // Check some degenerate cases
39   if (progName.length() == 0) // no program
40     return Path();
41   Path temp;
42   if (!temp.setFile(progName)) // invalid name
43     return Path();
44   if (temp.executable()) // already executable as is
45     return temp;
46
47   // At this point, the file name is valid and its not executable
48  
49   // Get the path. If its empty, we can't do anything to find it.
50   const char *PathStr = getenv("PATH");
51   if (PathStr == 0) 
52     return Path();
53
54   // Now we have a colon separated list of directories to search; try them.
55   unsigned PathLen = strlen(PathStr);
56   while (PathLen) {
57     // Find the first colon...
58     const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
59
60     // Check to see if this first directory contains the executable...
61     Path FilePath;
62     if (FilePath.setDirectory(std::string(PathStr,Colon))) {
63       FilePath.appendFile(progName);
64       if (FilePath.executable())
65         return FilePath;                    // Found the executable!
66     }
67
68     // Nope it wasn't in this directory, check the next path in the list!
69     PathLen -= Colon-PathStr;
70     PathStr = Colon;
71
72     // Advance past duplicate colons
73     while (*PathStr == ':') {
74       PathStr++;
75       PathLen--;
76     }
77   }
78   return Path();
79 }
80
81 static void RedirectFD(const std::string &File, int FD) {
82   if (File.empty()) return;  // Noop
83
84   // Open the file
85   int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
86   if (InFD == -1) {
87     ThrowErrno("Cannot open file '" + File + "' for "
88               + (FD == 0 ? "input" : "output") + "!\n");
89   }
90
91   dup2(InFD, FD);   // Install it as the requested FD
92   close(InFD);      // Close the original FD
93 }
94
95 static bool Timeout = false;
96 static void TimeOutHandler(int Sig) {
97   Timeout = true;
98 }
99
100 int 
101 Program::ExecuteAndWait(const Path& path, 
102                         const char** args,
103                         const char** envp,
104                         const Path** redirects,
105                         unsigned secondsToWait
106 ) {
107   if (!path.executable())
108     throw path.toString() + " is not executable"; 
109
110 #ifdef HAVE_SYS_WAIT_H
111   // Create a child process.
112   int child = fork();
113   switch (child) {
114     // An error occured:  Return to the caller.
115     case -1:
116       ThrowErrno(std::string("Couldn't execute program '") + path.toString() + 
117                  "'");
118       break;
119
120     // Child process: Execute the program.
121     case 0: {
122       // Redirect file descriptors...
123       if (redirects) {
124         if (redirects[0])
125           if (redirects[0]->isEmpty())
126             RedirectFD("/dev/null",0);
127           else
128             RedirectFD(redirects[0]->toString(), 0);
129         if (redirects[1])
130           if (redirects[1]->isEmpty())
131             RedirectFD("/dev/null",1);
132           else
133             RedirectFD(redirects[1]->toString(), 1);
134         if (redirects[1] && redirects[2] && 
135             *(redirects[1]) != *(redirects[2])) {
136           if (redirects[2]->isEmpty())
137             RedirectFD("/dev/null",2);
138           else
139             RedirectFD(redirects[2]->toString(), 2);
140         } else {
141           dup2(1, 2);
142         }
143       }
144
145       // Set up the environment
146       char** env = environ;
147       if (envp != 0)
148         env = (char**) envp;
149
150       // Execute!
151       execve (path.c_str(), (char** const)args, env);
152       // If the execve() failed, we should exit and let the parent pick up
153       // our non-zero exit status.
154       exit (errno);
155     }
156
157     // Parent process: Break out of the switch to do our processing.
158     default:
159       break;
160   }
161
162   // Make sure stderr and stdout have been flushed
163   std::cerr << std::flush;
164   std::cout << std::flush;
165   fsync(1);
166   fsync(2);
167
168   struct sigaction Act, Old;
169
170   // Install a timeout handler.
171   if (secondsToWait) {
172     Timeout = false;
173     Act.sa_sigaction = 0;
174     Act.sa_handler = TimeOutHandler;
175     sigemptyset(&Act.sa_mask);
176     Act.sa_flags = 0;
177     sigaction(SIGALRM, &Act, &Old);
178     alarm(secondsToWait);
179   }
180
181   // Parent process: Wait for the child process to terminate.
182   int status;
183   while (wait(&status) != child)
184     if (secondsToWait && errno == EINTR) {
185       // Kill the child.
186       kill(child, SIGKILL);
187         
188       // Turn off the alarm and restore the signal handler
189       alarm(0);
190       sigaction(SIGALRM, &Old, 0);
191
192       // Wait for child to die
193       if (wait(&status) != child)
194         ThrowErrno("Child timedout but wouldn't die");
195         
196       return -1;   // Timeout detected
197     } else {
198       ThrowErrno("Error waiting for child process");
199     }
200
201   // We exited normally without timeout, so turn off the timer.
202   if (secondsToWait) {
203     alarm(0);
204     sigaction(SIGALRM, &Old, 0);
205   }
206
207   // If the program exited normally with a zero exit status, return success!
208   if (WIFEXITED (status))
209     return WEXITSTATUS(status);
210   else if (WIFSIGNALED(status))
211     throw std::string("Program '") + path.toString() + 
212           "' received terminating signal.";
213     
214 #else
215   throw std::string(
216     "Program::ExecuteAndWait not implemented on this platform!\n");
217 #endif
218   return 0;
219 }
220
221 }
222 // vim: sw=2 smartindent smarttab tw=80 autoindent expandtab