Fix up error message.
[oota-llvm.git] / lib / Support / SystemUtils.cpp
1 //===- SystemUtils.h - Utilities to do low-level system stuff --*- C++ -*--===//
2 //
3 // This file contains functions used to do a variety of low-level, often
4 // system-specific, tasks.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "Support/SystemUtils.h"
9 #include <algorithm>
10 #include <fstream>
11 #include <iostream>
12 #include <cstdlib>
13 #include "Config/sys/types.h"
14 #include "Config/sys/stat.h"
15 #include "Config/fcntl.h"
16 #include "Config/sys/wait.h"
17 #include "Config/unistd.h"
18 #include "Config/errno.h"
19
20 /// isExecutableFile - This function returns true if the filename specified
21 /// exists and is executable.
22 ///
23 bool isExecutableFile(const std::string &ExeFileName) {
24   struct stat Buf;
25   if (stat(ExeFileName.c_str(), &Buf))
26     return false;  // Must not be executable!
27
28   if (!(Buf.st_mode & S_IFREG))
29     return false;                    // Not a regular file?
30
31   if (Buf.st_uid == getuid())        // Owner of file?
32     return Buf.st_mode & S_IXUSR;
33   else if (Buf.st_gid == getgid())   // In group of file?
34     return Buf.st_mode & S_IXGRP;
35   else                               // Unrelated to file?
36     return Buf.st_mode & S_IXOTH;
37 }
38
39 /// FindExecutable - Find a named executable, giving the argv[0] of program
40 /// being executed. This allows us to find another LLVM tool if it is built
41 /// into the same directory, but that directory is neither the current
42 /// directory, nor in the PATH.  If the executable cannot be found, return an
43 /// empty string.
44 /// 
45 std::string FindExecutable(const std::string &ExeName,
46                            const std::string &ProgramPath) {
47   // First check the directory that bugpoint is in.  We can do this if
48   // BugPointPath contains at least one / character, indicating that it is a
49   // relative path to bugpoint itself.
50   //
51   std::string Result = ProgramPath;
52   while (!Result.empty() && Result[Result.size()-1] != '/')
53     Result.erase(Result.size()-1, 1);
54
55   if (!Result.empty()) {
56     Result += ExeName;
57     if (isExecutableFile(Result)) return Result; // Found it?
58   }
59
60   // Okay, if the path to the program didn't tell us anything, try using the
61   // PATH environment variable.
62   const char *PathStr = getenv("PATH");
63   if (PathStr == 0) return "";
64
65   // Now we have a colon separated list of directories to search... try them...
66   unsigned PathLen = strlen(PathStr);
67   while (PathLen) {
68     // Find the first colon...
69     const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
70     
71     // Check to see if this first directory contains the executable...
72     std::string FilePath = std::string(PathStr, Colon) + '/' + ExeName;
73     if (isExecutableFile(FilePath))
74       return FilePath;                    // Found the executable!
75    
76     // Nope it wasn't in this directory, check the next range!
77     PathLen -= Colon-PathStr;
78     PathStr = Colon;
79     while (*PathStr == ':') {   // Advance past colons
80       PathStr++;
81       PathLen--;
82     }
83   }
84
85   // If we fell out, we ran out of directories in PATH to search, return failure
86   return "";
87 }
88
89 static void RedirectFD(const std::string &File, int FD) {
90   if (File.empty()) return;  // Noop
91
92   // Open the file
93   int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
94   if (InFD == -1) {
95     std::cerr << "Error opening file '" << File << "' for "
96               << (FD == 0 ? "input" : "output") << "!\n";
97     exit(1);
98   }
99
100   dup2(InFD, FD);   // Install it as the requested FD
101   close(InFD);      // Close the original FD
102 }
103
104 /// RunProgramWithTimeout - This function executes the specified program, with
105 /// the specified null-terminated argument array, with the stdin/out/err fd's
106 /// redirected, with a timeout specified on the command line.  This terminates
107 /// the calling program if there is an error executing the specified program.
108 /// It returns the return value of the program, or -1 if a timeout is detected.
109 ///
110 int RunProgramWithTimeout(const std::string &ProgramPath, const char **Args,
111                           const std::string &StdInFile,
112                           const std::string &StdOutFile,
113                           const std::string &StdErrFile) {
114
115   // FIXME: install sigalarm handler here for timeout...
116
117   int Child = fork();
118   switch (Child) {
119   case -1:
120     std::cerr << "ERROR forking!\n";
121     exit(1);
122   case 0:               // Child
123     RedirectFD(StdInFile, 0);      // Redirect file descriptors...
124     RedirectFD(StdOutFile, 1);
125     RedirectFD(StdErrFile, 2);
126
127     execv(ProgramPath.c_str(), (char *const *)Args);
128     std::cerr << "Error executing program: '" << ProgramPath;
129     for (; *Args; ++Args)
130       std::cerr << " " << *Args;
131     std::cerr << "'\n";
132     exit(1);
133
134   default: break;
135   }
136
137   // Make sure all output has been written while waiting
138   std::cout << std::flush;
139
140   int Status;
141   if (wait(&Status) != Child) {
142     if (errno == EINTR) {
143       static bool FirstTimeout = true;
144       if (FirstTimeout) {
145         std::cout <<
146  "*** Program execution timed out!  This mechanism is designed to handle\n"
147  "    programs stuck in infinite loops gracefully.  The -timeout option\n"
148  "    can be used to change the timeout threshold or disable it completely\n"
149  "    (with -timeout=0).  This message is only displayed once.\n";
150         FirstTimeout = false;
151       }
152       return -1;   // Timeout detected
153     }
154
155     std::cerr << "Error waiting for child process!\n";
156     exit(1);
157   }
158   return Status;
159 }
160
161
162 //
163 // Function: ExecWait ()
164 //
165 // Description:
166 //  This function executes a program with the specified arguments and
167 //  environment.  It then waits for the progarm to termiante and then returns
168 //  to the caller.
169 //
170 // Inputs:
171 //  argv - The arguments to the program as an array of C strings.  The first
172 //         argument should be the name of the program to execute, and the
173 //         last argument should be a pointer to NULL.
174 //
175 //  envp - The environment passes to the program as an array of C strings in
176 //         the form of "name=value" pairs.  The last element should be a
177 //         pointer to NULL.
178 //
179 // Outputs:
180 //  None.
181 //
182 // Return value:
183 //  0 - No errors.
184 //  1 - The program could not be executed.
185 //  1 - The program returned a non-zero exit status.
186 //  1 - The program terminated abnormally.
187 //
188 // Notes:
189 //  The program will inherit the stdin, stdout, and stderr file descriptors
190 //  as well as other various configuration settings (umask).
191 //
192 //  This function should not print anything to stdout/stderr on its own.  It is
193 //  a generic library function.  The caller or executed program should report
194 //  errors in the way it sees fit.
195 //
196 //  This function does not use $PATH to find programs.
197 //
198 int
199 ExecWait (const char * const old_argv[], const char * const old_envp[])
200 {
201   // Child process ID
202   register int child;
203
204   // Status from child process when it exits
205   int status;
206  
207   //
208   // Create local versions of the parameters that can be passed into execve()
209   // without creating const problems.
210   //
211   char ** const argv = (char ** const) old_argv;
212   char ** const envp = (char ** const) old_envp;
213
214   //
215   // Create a child process.
216   //
217   switch (child=fork())
218   {
219     //
220     // An error occured:  Return to the caller.
221     //
222     case -1:
223       return 1;
224       break;
225
226     //
227     // Child process: Execute the program.
228     //
229     case 0:
230       execve (argv[0], argv, envp);
231
232       //
233       // If the execve() failed, we should exit and let the parent pick up
234       // our non-zero exit status.
235       //
236       exit (1);
237       break;
238
239     //
240     // Parent process: Break out of the switch to do our processing.
241     //
242     default:
243       break;
244   }
245
246   //
247   // Parent process: Wait for the child process to termiante.
248   //
249   if ((wait (&status)) == -1)
250   {
251     return 1;
252   }
253
254   //
255   // If the program exited normally with a zero exit status, return success!
256   //
257   if (WIFEXITED (status) && (WEXITSTATUS(status) == 0))
258   {
259     return 0;
260   }
261
262   //
263   // Otherwise, return failure.
264   //
265   return 1;
266 }
267