For PR351:Remove the file type checking methods (now in sys::Path)
[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 "llvm/Support/FileUtilities.h"
16 #include "llvm/Support/DataTypes.h"
17 #include "llvm/Config/unistd.h"
18 #include "llvm/Config/fcntl.h"
19 #include "llvm/Config/sys/types.h"
20 #include "llvm/Config/sys/stat.h"
21 #include "llvm/Config/sys/mman.h"
22 #include "llvm/Config/alloca.h"
23 #include <cerrno>
24 #include <cstdio>
25 #include <fstream>
26 #include <iostream>
27 using namespace llvm;
28
29 /// DiffFiles - Compare the two files specified, returning true if they are
30 /// different or if there is a file error.  If you specify a string to fill in
31 /// for the error option, it will set the string to an error message if an error
32 /// occurs, allowing the caller to distinguish between a failed diff and a file
33 /// system error.
34 ///
35 bool llvm::DiffFiles(const std::string &FileA, const std::string &FileB,
36                      std::string *Error) {
37   std::ifstream FileAStream(FileA.c_str());
38   if (!FileAStream) {
39     if (Error) *Error = "Couldn't open file '" + FileA + "'";
40     return true;
41   }
42
43   std::ifstream FileBStream(FileB.c_str());
44   if (!FileBStream) {
45     if (Error) *Error = "Couldn't open file '" + FileB + "'";
46     return true;
47   }
48
49   // Compare the two files...
50   int C1, C2;
51   do {
52     C1 = FileAStream.get();
53     C2 = FileBStream.get();
54     if (C1 != C2) return true;
55   } while (C1 != EOF);
56
57   return false;
58 }
59
60
61 /// CopyFile - Copy the specified source file to the specified destination,
62 /// overwriting destination if it exists.  This returns true on failure.
63 ///
64 bool llvm::CopyFile(const std::string &Dest, const std::string &Src) {
65   FDHandle InFD(open(Src.c_str(), O_RDONLY));
66   if (InFD == -1) return true;
67
68   FileRemover FR(Dest);
69
70   FDHandle OutFD(open(Dest.c_str(), O_WRONLY|O_CREAT, 0666));
71   if (OutFD == -1) return true;
72
73   char Buffer[16*1024];
74   while (ssize_t Amt = read(InFD, Buffer, 16*1024)) {
75     if (Amt == -1) {
76       if (errno != EINTR) return true;  // Error reading the file.
77     } else {
78       char *BufPtr = Buffer;
79       while (Amt) {
80         ssize_t AmtWritten = write(OutFD, BufPtr, Amt);
81         if (AmtWritten == -1) {
82           if (errno != EINTR) return true;  // Error writing the file.
83         } else {
84           Amt -= AmtWritten;
85           BufPtr += AmtWritten;
86         }
87       }
88     }
89   }
90
91   FR.releaseFile();  // Success!
92   return false;
93 }
94
95
96 /// MoveFileOverIfUpdated - If the file specified by New is different than Old,
97 /// or if Old does not exist, move the New file over the Old file.  Otherwise,
98 /// remove the New file.
99 ///
100 void llvm::MoveFileOverIfUpdated(const std::string &New,
101                                  const std::string &Old) {
102   if (DiffFiles(New, Old)) {
103     if (std::rename(New.c_str(), Old.c_str()))
104       std::cerr << "Error renaming '" << New << "' to '" << Old << "'!\n";
105   } else {
106     std::remove(New.c_str());
107   }  
108 }
109
110 /// removeFile - Delete the specified file
111 ///
112 void llvm::removeFile(const std::string &Filename) {
113   std::remove(Filename.c_str());
114 }
115
116 /// getUniqueFilename - Return a filename with the specified prefix.  If the
117 /// file does not exist yet, return it, otherwise add a suffix to make it
118 /// unique.
119 ///
120 std::string llvm::getUniqueFilename(const std::string &FilenameBase) {
121   if (!std::ifstream(FilenameBase.c_str()))
122     return FilenameBase;    // Couldn't open the file? Use it!
123
124   // Create a pattern for mkstemp...
125   char *FNBuffer = new char[FilenameBase.size()+8];
126   strcpy(FNBuffer, FilenameBase.c_str());
127   strcpy(FNBuffer+FilenameBase.size(), "-XXXXXX");
128
129   // Agree on a temporary file name to use....
130 #if defined(HAVE_MKSTEMP) && !defined(_MSC_VER)
131   int TempFD;
132   if ((TempFD = mkstemp(FNBuffer)) == -1) {
133     // FIXME: this should return an emtpy string or something and allow the
134     // caller to deal with the error!
135     std::cerr << "bugpoint: ERROR: Cannot create temporary file in the current "
136               << " directory!\n";
137     exit(1);
138   }
139
140   // We don't need to hold the temp file descriptor... we will trust that no one
141   // will overwrite/delete the file while we are working on it...
142   close(TempFD);
143 #else
144   // If we don't have mkstemp, use the old and obsolete mktemp function.
145   if (mktemp(FNBuffer) == 0) {
146     // FIXME: this should return an emtpy string or something and allow the
147     // caller to deal with the error!
148     std::cerr << "bugpoint: ERROR: Cannot create temporary file in the current "
149               << " directory!\n";
150     exit(1);
151   }
152 #endif
153
154   std::string Result(FNBuffer);
155   delete[] FNBuffer;
156   return Result;
157 }
158
159 static bool AddPermissionsBits (const std::string &Filename, int 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   int mask = umask(0777); // The arg. to umask is arbitrary.
165   umask(mask);            // Restore the umask.
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 /// ReadFileIntoAddressSpace - Attempt to map the specific file into the
219 /// address space of the current process for reading.  If this succeeds,
220 /// return the address of the buffer and the length of the file mapped.  On
221 /// failure, return null.
222 void *llvm::ReadFileIntoAddressSpace(const std::string &Filename, 
223                                      unsigned &Length) {
224 #if defined(HAVE_MMAP_FILE) && !defined(_MSC_VER)
225   Length = (unsigned)getFileSize(Filename);
226   if ((int)Length == -1) return 0;
227
228   FDHandle FD(open(Filename.c_str(), O_RDONLY));
229   if (FD == -1) return 0;
230
231   // If the file has a length of zero, mmap might return a null pointer.  In 
232   // this case, allocate a single byte of memory and return it instead.
233   if (Length == 0)
234     return malloc(1);
235
236   // mmap in the file all at once...
237   void *Buffer = (void*)mmap(0, Length, PROT_READ, MAP_PRIVATE, FD, 0);
238
239   if (Buffer == (void*)MAP_FAILED)
240     return 0;
241
242   return Buffer;
243 #else
244   // FIXME: implement with read/write
245 #error Unimplemented ReadFileIntoAddressSpace - need to use read/write.
246   return 0;
247 #endif
248 }
249
250 /// UnmapFileFromAddressSpace - Remove the specified file from the current
251 /// address space.
252 void llvm::UnmapFileFromAddressSpace(void *Buffer, unsigned Length) {
253 #if defined(HAVE_MMAP_FILE) && !defined(_MSC_VER)
254   if (Length)
255     munmap((char*)Buffer, Length);
256   else
257     free(Buffer);  // Zero byte files are malloc(1)'s.
258 #else
259   free(Buffer);
260 #endif
261 }
262
263 //===----------------------------------------------------------------------===//
264 // FDHandle class implementation
265 //
266
267 FDHandle::~FDHandle() throw() {
268   if (FD != -1) close(FD);
269 }
270
271 FDHandle &FDHandle::operator=(int fd) throw() {
272   if (FD != -1) close(FD);
273   FD = fd;
274   return *this;
275 }
276