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 "Support/FileUtilities.h"
16 #include "Config/unistd.h"
17 #include "Config/fcntl.h"
18 #include "Config/sys/stat.h"
19 #include "Config/sys/types.h"
20 #include "Config/sys/mman.h"
26 /// CheckMagic - Returns true IFF the file named FN begins with Magic. FN must
27 /// name a readable file.
29 bool llvm::CheckMagic(const std::string &FN, const std::string &Magic) {
30 char buf[1 + Magic.size ()];
31 std::ifstream f (FN.c_str ());
32 f.read (buf, Magic.size ());
33 buf[Magic.size ()] = '\0';
37 /// IsArchive - Returns true IFF the file named FN appears to be a "ar" library
38 /// archive. The file named FN must exist.
40 bool llvm::IsArchive(const std::string &FN) {
41 // Inspect the beginning of the file to see if it contains the "ar"
42 // library archive format magic string.
43 return CheckMagic (FN, "!<arch>\012");
46 /// IsBytecode - Returns true IFF the file named FN appears to be an LLVM
47 /// bytecode file. The file named FN must exist.
49 bool llvm::IsBytecode(const std::string &FN) {
50 // Inspect the beginning of the file to see if it contains the LLVM
51 // bytecode format magic string.
52 return CheckMagic (FN, "llvm");
55 /// IsSharedObject - Returns trus IFF the file named FN appears to be a shared
56 /// object with an ELF header. The file named FN must exist.
58 bool llvm::IsSharedObject(const std::string &FN) {
59 // Inspect the beginning of the file to see if it contains the ELF shared
60 // object magic string.
61 static const char elfMagic[] = { 0x7f, 'E', 'L', 'F', '\0' };
62 return CheckMagic(FN, elfMagic);
65 /// FileOpenable - Returns true IFF Filename names an existing regular
66 /// file which we can successfully open.
68 bool llvm::FileOpenable(const std::string &Filename) {
70 if (stat (Filename.c_str (), &s) == -1)
71 return false; // Cannot stat file
72 if (!S_ISREG (s.st_mode))
73 return false; // File is not a regular file
74 std::ifstream FileStream (Filename.c_str ());
76 return false; // File is not openable
80 /// DiffFiles - Compare the two files specified, returning true if they are
81 /// different or if there is a file error. If you specify a string to fill in
82 /// for the error option, it will set the string to an error message if an error
83 /// occurs, allowing the caller to distinguish between a failed diff and a file
86 bool llvm::DiffFiles(const std::string &FileA, const std::string &FileB,
88 std::ifstream FileAStream(FileA.c_str());
90 if (Error) *Error = "Couldn't open file '" + FileA + "'";
94 std::ifstream FileBStream(FileB.c_str());
96 if (Error) *Error = "Couldn't open file '" + FileB + "'";
100 // Compare the two files...
103 C1 = FileAStream.get();
104 C2 = FileBStream.get();
105 if (C1 != C2) return true;
112 /// MoveFileOverIfUpdated - If the file specified by New is different than Old,
113 /// or if Old does not exist, move the New file over the Old file. Otherwise,
114 /// remove the New file.
116 void llvm::MoveFileOverIfUpdated(const std::string &New,
117 const std::string &Old) {
118 if (DiffFiles(New, Old)) {
119 if (std::rename(New.c_str(), Old.c_str()))
120 std::cerr << "Error renaming '" << New << "' to '" << Old << "'!\n";
122 std::remove(New.c_str());
126 /// removeFile - Delete the specified file
128 void llvm::removeFile(const std::string &Filename) {
129 std::remove(Filename.c_str());
132 /// getUniqueFilename - Return a filename with the specified prefix. If the
133 /// file does not exist yet, return it, otherwise add a suffix to make it
136 std::string llvm::getUniqueFilename(const std::string &FilenameBase) {
137 if (!std::ifstream(FilenameBase.c_str()))
138 return FilenameBase; // Couldn't open the file? Use it!
140 // Create a pattern for mkstemp...
141 char *FNBuffer = new char[FilenameBase.size()+8];
142 strcpy(FNBuffer, FilenameBase.c_str());
143 strcpy(FNBuffer+FilenameBase.size(), "-XXXXXX");
145 // Agree on a temporary file name to use....
147 if ((TempFD = mkstemp(FNBuffer)) == -1) {
148 std::cerr << "bugpoint: ERROR: Cannot create temporary file in the current "
153 // We don't need to hold the temp file descriptor... we will trust that no one
154 // will overwrite/delete the file while we are working on it...
156 std::string Result(FNBuffer);
161 static bool AddPermissionsBits (const std::string &Filename, mode_t bits) {
162 // Get the umask value from the operating system. We want to use it
163 // when changing the file's permissions. Since calling umask() sets
164 // the umask and returns its old value, we must call it a second
165 // time to reset it to the user's preference.
166 mode_t mask = umask (0777); // The arg. to umask is arbitrary...
169 // Get the file's current mode.
171 if ((stat (Filename.c_str(), &st)) == -1)
174 // Change the file to have whichever permissions bits from 'bits'
175 // that the umask would not disable.
176 if ((chmod(Filename.c_str(), (st.st_mode | (bits & ~mask)))) == -1)
182 /// MakeFileExecutable - Make the file named Filename executable by
183 /// setting whichever execute permissions bits the process's current
184 /// umask would allow. Filename must name an existing file or
185 /// directory. Returns true on success, false on error.
187 bool llvm::MakeFileExecutable(const std::string &Filename) {
188 return AddPermissionsBits(Filename, 0111);
191 /// MakeFileReadable - Make the file named Filename readable by
192 /// setting whichever read permissions bits the process's current
193 /// umask would allow. Filename must name an existing file or
194 /// directory. Returns true on success, false on error.
196 bool llvm::MakeFileReadable(const std::string &Filename) {
197 return AddPermissionsBits(Filename, 0444);
200 /// getFileSize - Return the size of the specified file in bytes, or -1 if the
201 /// file cannot be read or does not exist.
202 long long llvm::getFileSize(const std::string &Filename) {
204 if (stat(Filename.c_str(), &StatBuf) == -1)
206 return StatBuf.st_size;
209 /// getFileTimestamp - Get the last modified time for the specified file in an
210 /// unspecified format. This is useful to allow checking to see if a file was
211 /// updated since that last time the timestampt was aquired. If the file does
212 /// not exist or there is an error getting the time-stamp, zero is returned.
213 unsigned long long llvm::getFileTimestamp(const std::string &Filename) {
215 if (stat(Filename.c_str(), &StatBuf) == -1)
217 return StatBuf.st_mtime;
220 /// ReadFileIntoAddressSpace - Attempt to map the specific file into the
221 /// address space of the current process for reading. If this succeeds,
222 /// return the address of the buffer and the length of the file mapped. On
223 /// failure, return null.
224 void *llvm::ReadFileIntoAddressSpace(const std::string &Filename,
226 #ifdef HAVE_MMAP_FILE
227 Length = getFileSize(Filename);
228 if ((int)Length == -1) return 0;
230 FDHandle FD(open(Filename.c_str(), O_RDONLY));
231 if (FD == -1) return 0;
233 // If the file has a length of zero, mmap might return a null pointer. In
234 // this case, allocate a single byte of memory and return it instead.
238 // mmap in the file all at once...
239 void *Buffer = (void*)mmap(0, Length, PROT_READ, MAP_PRIVATE, FD, 0);
241 if (Buffer == (void*)MAP_FAILED)
246 // FIXME: implement with read/write
251 /// UnmapFileFromAddressSpace - Remove the specified file from the current
253 void llvm::UnmapFileFromAddressSpace(void *Buffer, unsigned Length) {
254 #ifdef HAVE_MMAP_FILE
256 munmap((char*)Buffer, Length);
258 free(Buffer); // Zero byte files are malloc(1)'s.
264 //===----------------------------------------------------------------------===//
265 // FDHandle class implementation
268 FDHandle::~FDHandle() throw() {
269 if (FD != -1) close(FD);
272 FDHandle &FDHandle::operator=(int fd) throw() {
273 if (FD != -1) close(FD);