Add new function
[oota-llvm.git] / lib / Support / FileUtilities.cpp
1 //===- Support/FileUtilities.cpp - File System Utilities ------------------===//
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 implements a family of utility functions which are useful for doing
11 // various things with files.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "Support/FileUtilities.h"
16 #include "Config/unistd.h"
17 #include "Config/sys/stat.h"
18 #include "Config/sys/types.h"
19 #include <fstream>
20 #include <iostream>
21 #include <cstdio>
22 using namespace llvm;
23
24 /// CheckMagic - Returns true IFF the file named FN begins with Magic. FN must
25 /// name a readable file.
26 ///
27 bool llvm::CheckMagic(const std::string &FN, const std::string &Magic) {
28   char buf[1 + Magic.size ()];
29   std::ifstream f (FN.c_str ());
30   f.read (buf, Magic.size ());
31   buf[Magic.size ()] = '\0';
32   return Magic == buf;
33 }
34
35 /// IsArchive - Returns true IFF the file named FN appears to be a "ar" library
36 /// archive. The file named FN must exist.
37 ///
38 bool llvm::IsArchive(const std::string &FN) {
39   // Inspect the beginning of the file to see if it contains the "ar"
40   // library archive format magic string.
41   return CheckMagic (FN, "!<arch>\012");
42 }
43
44 /// IsBytecode - Returns true IFF the file named FN appears to be an LLVM
45 /// bytecode file. The file named FN must exist.
46 ///
47 bool llvm::IsBytecode(const std::string &FN) {
48   // Inspect the beginning of the file to see if it contains the LLVM
49   // bytecode format magic string.
50   return CheckMagic (FN, "llvm");
51 }
52
53 /// IsSharedObject - Returns trus IFF the file named FN appears to be a shared
54 /// object with an ELF header. The file named FN must exist.
55 ///
56 bool llvm::IsSharedObject(const std::string &FN) {
57   // Inspect the beginning of the file to see if it contains the ELF shared
58   // object magic string.
59   static const char elfMagic[] = { 0x7f, 'E', 'L', 'F', '\0' };
60   return CheckMagic(FN, elfMagic);
61 }
62
63 /// FileOpenable - Returns true IFF Filename names an existing regular
64 /// file which we can successfully open.
65 ///
66 bool llvm::FileOpenable(const std::string &Filename) {
67   struct stat s;
68   if (stat (Filename.c_str (), &s) == -1)
69     return false; // Cannot stat file
70   if (!S_ISREG (s.st_mode))
71     return false; // File is not a regular file
72   std::ifstream FileStream (Filename.c_str ());
73   if (!FileStream)
74     return false; // File is not openable
75   return true;
76 }
77
78 /// DiffFiles - Compare the two files specified, returning true if they are
79 /// different or if there is a file error.  If you specify a string to fill in
80 /// for the error option, it will set the string to an error message if an error
81 /// occurs, allowing the caller to distinguish between a failed diff and a file
82 /// system error.
83 ///
84 bool llvm::DiffFiles(const std::string &FileA, const std::string &FileB,
85                      std::string *Error) {
86   std::ifstream FileAStream(FileA.c_str());
87   if (!FileAStream) {
88     if (Error) *Error = "Couldn't open file '" + FileA + "'";
89     return true;
90   }
91
92   std::ifstream FileBStream(FileB.c_str());
93   if (!FileBStream) {
94     if (Error) *Error = "Couldn't open file '" + FileB + "'";
95     return true;
96   }
97
98   // Compare the two files...
99   int C1, C2;
100   do {
101     C1 = FileAStream.get();
102     C2 = FileBStream.get();
103     if (C1 != C2) return true;
104   } while (C1 != EOF);
105
106   return false;
107 }
108
109
110 /// MoveFileOverIfUpdated - If the file specified by New is different than Old,
111 /// or if Old does not exist, move the New file over the Old file.  Otherwise,
112 /// remove the New file.
113 ///
114 void llvm::MoveFileOverIfUpdated(const std::string &New,
115                                  const std::string &Old) {
116   if (DiffFiles(New, Old)) {
117     if (std::rename(New.c_str(), Old.c_str()))
118       std::cerr << "Error renaming '" << New << "' to '" << Old << "'!\n";
119   } else {
120     std::remove(New.c_str());
121   }  
122 }
123
124 /// removeFile - Delete the specified file
125 ///
126 void llvm::removeFile(const std::string &Filename) {
127   std::remove(Filename.c_str());
128 }
129
130 /// getUniqueFilename - Return a filename with the specified prefix.  If the
131 /// file does not exist yet, return it, otherwise add a suffix to make it
132 /// unique.
133 ///
134 std::string llvm::getUniqueFilename(const std::string &FilenameBase) {
135   if (!std::ifstream(FilenameBase.c_str()))
136     return FilenameBase;    // Couldn't open the file? Use it!
137
138   // Create a pattern for mkstemp...
139   char *FNBuffer = new char[FilenameBase.size()+8];
140   strcpy(FNBuffer, FilenameBase.c_str());
141   strcpy(FNBuffer+FilenameBase.size(), "-XXXXXX");
142
143   // Agree on a temporary file name to use....
144   int TempFD;
145   if ((TempFD = mkstemp(FNBuffer)) == -1) {
146     std::cerr << "bugpoint: ERROR: Cannot create temporary file in the current "
147               << " directory!\n";
148     exit(1);
149   }
150
151   // We don't need to hold the temp file descriptor... we will trust that no one
152   // will overwrite/delete the file while we are working on it...
153   close(TempFD);
154   std::string Result(FNBuffer);
155   delete[] FNBuffer;
156   return Result;
157 }
158
159 static bool AddPermissionsBits (const std::string &Filename, mode_t bits) {
160   // Get the umask value from the operating system.  We want to use it
161   // when changing the file's permissions. Since calling umask() sets
162   // the umask and returns its old value, we must call it a second
163   // time to reset it to the user's preference.
164   mode_t mask = umask (0777); // The arg. to umask is arbitrary...
165   umask (mask);
166
167   // Get the file's current mode.
168   struct stat st;
169   if ((stat (Filename.c_str(), &st)) == -1)
170     return false;
171
172   // Change the file to have whichever permissions bits from 'bits'
173   // that the umask would not disable.
174   if ((chmod(Filename.c_str(), (st.st_mode | (bits & ~mask)))) == -1)
175     return false;
176
177   return true;
178 }
179
180 /// MakeFileExecutable - Make the file named Filename executable by
181 /// setting whichever execute permissions bits the process's current
182 /// umask would allow. Filename must name an existing file or
183 /// directory.  Returns true on success, false on error.
184 ///
185 bool llvm::MakeFileExecutable(const std::string &Filename) {
186   return AddPermissionsBits(Filename, 0111);
187 }
188
189 /// MakeFileReadable - Make the file named Filename readable by
190 /// setting whichever read permissions bits the process's current
191 /// umask would allow. Filename must name an existing file or
192 /// directory.  Returns true on success, false on error.
193 ///
194 bool llvm::MakeFileReadable(const std::string &Filename) {
195   return AddPermissionsBits(Filename, 0444);
196 }
197
198 /// getFileSize - Return the size of the specified file in bytes, or -1 if the
199 /// file cannot be read or does not exist.
200 long long llvm::getFileSize(const std::string &Filename) {
201   struct stat StatBuf;
202   if (stat(Filename.c_str(), &StatBuf) == -1)
203     return -1;
204   return StatBuf.st_size;  
205 }
206
207 /// getFileTimestamp - Get the last modified time for the specified file in an
208 /// unspecified format.  This is useful to allow checking to see if a file was
209 /// updated since that last time the timestampt was aquired.  If the file does
210 /// not exist or there is an error getting the time-stamp, zero is returned.
211 unsigned long long llvm::getFileTimestamp(const std::string &Filename) {
212   struct stat StatBuf;
213   if (stat(Filename.c_str(), &StatBuf) == -1)
214     return 0;
215   return StatBuf.st_mtime;  
216 }
217
218
219
220
221 //===----------------------------------------------------------------------===//
222 // FDHandle class implementation
223 //
224
225 FDHandle::~FDHandle() throw() {
226   if (FD != -1) close(FD);
227 }
228
229 FDHandle &FDHandle::operator=(int fd) throw() {
230   if (FD != -1) close(FD);
231   FD = fd;
232   return *this;
233 }
234