New files for miscompilation detection
[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 "SystemUtils.h"
9 #include <algorithm>
10 #include <fstream>
11 #include <stdlib.h>
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <fcntl.h>
15 #include <sys/wait.h>
16 #include <unistd.h>
17 #include <errno.h>
18
19 /// removeFile - Delete the specified file
20 ///
21 void removeFile(const std::string &Filename) {
22   unlink(Filename.c_str());
23 }
24
25 /// getUniqueFilename - Return a filename with the specified prefix.  If the
26 /// file does not exist yet, return it, otherwise add a suffix to make it
27 /// unique.
28 ///
29 std::string getUniqueFilename(const std::string &FilenameBase) {
30   if (!std::ifstream(FilenameBase.c_str()))
31     return FilenameBase;    // Couldn't open the file? Use it!
32
33   // Create a pattern for mkstemp...
34   char *FNBuffer = (char*)alloca(FilenameBase.size()+8);
35   strcpy(FNBuffer, FilenameBase.c_str());
36   strcpy(FNBuffer+FilenameBase.size(), "-XXXXXX");
37
38   // Agree on a temporary file name to use....
39   int TempFD;
40   if ((TempFD = mkstemp(FNBuffer)) == -1) {
41     std::cerr << "bugpoint: ERROR: Cannot create temporary file in the current "
42               << " directory!\n";
43     exit(1);
44   }
45
46   // We don't need to hold the temp file descriptor... we will trust that noone
47   // will overwrite/delete the file while we are working on it...
48   close(TempFD);
49   return FNBuffer;
50 }
51
52 /// isExecutableFile - This function returns true if the filename specified
53 /// exists and is executable.
54 ///
55 bool isExecutableFile(const std::string &ExeFileName) {
56   struct stat Buf;
57   if (stat(ExeFileName.c_str(), &Buf))
58     return false;  // Must not be executable!
59
60   if (!(Buf.st_mode & S_IFREG))
61     return false;                    // Not a regular file?
62
63   if (Buf.st_uid == getuid())        // Owner of file?
64     return Buf.st_mode & S_IXUSR;
65   else if (Buf.st_gid == getgid())   // In group of file?
66     return Buf.st_mode & S_IXGRP;
67   else                               // Unrelated to file?
68     return Buf.st_mode & S_IXOTH;
69 }
70
71
72 // FindExecutable - Find a named executable, giving the argv[0] of bugpoint.
73 // This assumes the executable is in the same directory as bugpoint itself.
74 // If the executable cannot be found, return an empty string.
75 //
76 std::string FindExecutable(const std::string &ExeName,
77                            const std::string &BugPointPath) {
78   // First check the directory that bugpoint is in.  We can do this if
79   // BugPointPath contains at least one / character, indicating that it is a
80   // relative path to bugpoint itself.
81   //
82   std::string Result = BugPointPath;
83   while (!Result.empty() && Result[Result.size()-1] != '/')
84     Result.erase(Result.size()-1, 1);
85
86   if (!Result.empty()) {
87     Result += ExeName;
88     if (isExecutableFile(Result)) return Result; // Found it?
89   }
90
91   // Okay, if the path to bugpoint didn't tell us anything, try using the PATH
92   // environment variable.
93   const char *PathStr = getenv("PATH");
94   if (PathStr == 0) return "";
95
96   // Now we have a colon seperated list of directories to search... try them...
97   unsigned PathLen = strlen(PathStr);
98   while (PathLen) {
99     // Find the first colon...
100     const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
101     
102     // Check to see if this first directory contains the executable...
103     std::string FilePath = std::string(PathStr, Colon) + '/' + ExeName;
104     if (isExecutableFile(FilePath))
105       return FilePath;                    // Found the executable!
106    
107     // Nope it wasn't in this directory, check the next range!
108     PathLen -= Colon-PathStr;
109     PathStr = Colon;
110     while (*PathStr == ':') {   // Advance past colons
111       PathStr++;
112       PathLen--;
113     }
114   }
115
116   // If we fell out, we ran out of directories in PATH to search, return failure
117   return "";
118 }
119
120 static void RedirectFD(const std::string &File, int FD) {
121   if (File.empty()) return;  // Noop
122
123   // Open the file
124   int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
125   if (InFD == -1) {
126     std::cerr << "Error opening file '" << File << "' for "
127               << (FD == 0 ? "input" : "output") << "!\n";
128     exit(1);
129   }
130
131   dup2(InFD, FD);   // Install it as the requested FD
132   close(InFD);      // Close the original FD
133 }
134
135 /// RunProgramWithTimeout - This function executes the specified program, with
136 /// the specified null-terminated argument array, with the stdin/out/err fd's
137 /// redirected, with a timeout specified on the commandline.  This terminates
138 /// the calling program if there is an error executing the specified program.
139 /// It returns the return value of the program, or -1 if a timeout is detected.
140 ///
141 int RunProgramWithTimeout(const std::string &ProgramPath, const char **Args,
142                           const std::string &StdInFile,
143                           const std::string &StdOutFile,
144                           const std::string &StdErrFile) {
145
146   // FIXME: install sigalarm handler here for timeout...
147
148   int Child = fork();
149   switch (Child) {
150   case -1:
151     std::cerr << "ERROR forking!\n";
152     exit(1);
153   case 0:               // Child
154     RedirectFD(StdInFile, 0);      // Redirect file descriptors...
155     RedirectFD(StdOutFile, 1);
156     RedirectFD(StdErrFile, 2);
157
158     execv(ProgramPath.c_str(), (char *const *)Args);
159     std::cerr << "Error executing program '" << ProgramPath;
160     for (; *Args; ++Args)
161       std::cerr << " " << *Args;
162     exit(1);
163
164   default: break;
165   }
166
167   // Make sure all output has been written while waiting
168   std::cout << std::flush;
169
170   int Status;
171   if (wait(&Status) != Child) {
172     if (errno == EINTR) {
173       static bool FirstTimeout = true;
174       if (FirstTimeout) {
175         std::cout <<
176  "*** Program execution timed out!  This mechanism is designed to handle\n"
177  "    programs stuck in infinite loops gracefully.  The -timeout option\n"
178  "    can be used to change the timeout threshold or disable it completely\n"
179  "    (with -timeout=0).  This message is only displayed once.\n";
180         FirstTimeout = false;
181       }
182       return -1;   // Timeout detected
183     }
184
185     std::cerr << "Error waiting for child process!\n";
186     exit(1);
187   }
188   return Status;
189 }