1 //===- Support/FileUtilities.cpp - File System Utilities ------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements a family of utility functions which are useful for doing
11 // various things with files.
13 //===----------------------------------------------------------------------===//
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"
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
35 bool llvm::DiffFiles(const std::string &FileA, const std::string &FileB,
37 std::ifstream FileAStream(FileA.c_str());
39 if (Error) *Error = "Couldn't open file '" + FileA + "'";
43 std::ifstream FileBStream(FileB.c_str());
45 if (Error) *Error = "Couldn't open file '" + FileB + "'";
49 // Compare the two files...
52 C1 = FileAStream.get();
53 C2 = FileBStream.get();
54 if (C1 != C2) return true;
61 /// CopyFile - Copy the specified source file to the specified destination,
62 /// overwriting destination if it exists. This returns true on failure.
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;
70 FDHandle OutFD(open(Dest.c_str(), O_WRONLY|O_CREAT, 0666));
71 if (OutFD == -1) return true;
74 while (ssize_t Amt = read(InFD, Buffer, 16*1024)) {
76 if (errno != EINTR) return true; // Error reading the file.
78 char *BufPtr = Buffer;
80 ssize_t AmtWritten = write(OutFD, BufPtr, Amt);
81 if (AmtWritten == -1) {
82 if (errno != EINTR) return true; // Error writing the file.
91 FR.releaseFile(); // Success!
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.
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";
106 std::remove(New.c_str());
110 /// removeFile - Delete the specified file
112 void llvm::removeFile(const std::string &Filename) {
113 std::remove(Filename.c_str());
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
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!
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");
129 // Agree on a temporary file name to use....
130 #if defined(HAVE_MKSTEMP) && !defined(_MSC_VER)
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 "
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...
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 "
154 std::string Result(FNBuffer);
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.
167 // Get the file's current mode.
169 if ((stat(Filename.c_str(), &st)) == -1)
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)
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.
185 bool llvm::MakeFileExecutable(const std::string &Filename) {
186 return AddPermissionsBits(Filename, 0111);
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.
194 bool llvm::MakeFileReadable(const std::string &Filename) {
195 return AddPermissionsBits(Filename, 0444);
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) {
202 if (stat(Filename.c_str(), &StatBuf) == -1)
204 return StatBuf.st_size;
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) {
213 if (stat(Filename.c_str(), &StatBuf) == -1)
215 return StatBuf.st_mtime;
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,
224 #if defined(HAVE_MMAP_FILE) && !defined(_MSC_VER)
225 Length = (unsigned)getFileSize(Filename);
226 if ((int)Length == -1) return 0;
228 FDHandle FD(open(Filename.c_str(), O_RDONLY));
229 if (FD == -1) return 0;
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.
236 // mmap in the file all at once...
237 void *Buffer = (void*)mmap(0, Length, PROT_READ, MAP_PRIVATE, FD, 0);
239 if (Buffer == (void*)MAP_FAILED)
244 // FIXME: implement with read/write
245 #error Unimplemented ReadFileIntoAddressSpace - need to use read/write.
250 /// UnmapFileFromAddressSpace - Remove the specified file from the current
252 void llvm::UnmapFileFromAddressSpace(void *Buffer, unsigned Length) {
253 #if defined(HAVE_MMAP_FILE) && !defined(_MSC_VER)
255 munmap((char*)Buffer, Length);
257 free(Buffer); // Zero byte files are malloc(1)'s.
263 //===----------------------------------------------------------------------===//
264 // FDHandle class implementation
267 FDHandle::~FDHandle() throw() {
268 if (FD != -1) close(FD);
271 FDHandle &FDHandle::operator=(int fd) throw() {
272 if (FD != -1) close(FD);