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