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