blob: bd5cf09be7cdd44eb35f7dd5c7884315b0dd674f [file] [log] [blame]
Chris Lattner7a6ff2b2003-08-01 21:16:14 +00001//===- Support/FileUtilities.cpp - File System Utilities ------------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
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//===----------------------------------------------------------------------===//
Chris Lattner7a6ff2b2003-08-01 21:16:14 +00009//
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"
Misha Brukmanda81eca2003-08-07 21:35:41 +000016#include "Config/unistd.h"
Chris Lattnereb082992004-05-28 00:23:48 +000017#include "Config/fcntl.h"
John Criswell6991a032003-09-02 20:14:57 +000018#include "Config/sys/stat.h"
19#include "Config/sys/types.h"
Chris Lattnereb082992004-05-28 00:23:48 +000020#include "Config/sys/mman.h"
Chris Lattner7a6ff2b2003-08-01 21:16:14 +000021#include <fstream>
22#include <iostream>
23#include <cstdio>
Chris Lattner2cdd21c2003-12-14 21:35:53 +000024using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000025
Brian Gaekea2302ff2003-11-11 21:53:50 +000026/// CheckMagic - Returns true IFF the file named FN begins with Magic. FN must
27/// name a readable file.
28///
Chris Lattner2cdd21c2003-12-14 21:35:53 +000029bool llvm::CheckMagic(const std::string &FN, const std::string &Magic) {
Brian Gaekea2302ff2003-11-11 21:53:50 +000030 char buf[1 + Magic.size ()];
31 std::ifstream f (FN.c_str ());
32 f.read (buf, Magic.size ());
33 buf[Magic.size ()] = '\0';
34 return Magic == buf;
35}
36
37/// IsArchive - Returns true IFF the file named FN appears to be a "ar" library
38/// archive. The file named FN must exist.
39///
Chris Lattner2cdd21c2003-12-14 21:35:53 +000040bool llvm::IsArchive(const std::string &FN) {
Brian Gaekea2302ff2003-11-11 21:53:50 +000041 // 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");
44}
45
46/// IsBytecode - Returns true IFF the file named FN appears to be an LLVM
47/// bytecode file. The file named FN must exist.
48///
Chris Lattner2cdd21c2003-12-14 21:35:53 +000049bool llvm::IsBytecode(const std::string &FN) {
Brian Gaekea2302ff2003-11-11 21:53:50 +000050 // Inspect the beginning of the file to see if it contains the LLVM
51 // bytecode format magic string.
52 return CheckMagic (FN, "llvm");
53}
54
Misha Brukman17cca962003-11-24 05:28:12 +000055/// 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.
57///
Chris Lattner2cdd21c2003-12-14 21:35:53 +000058bool llvm::IsSharedObject(const std::string &FN) {
Misha Brukman971a7b82003-11-24 05:36:38 +000059 // Inspect the beginning of the file to see if it contains the ELF shared
60 // object magic string.
Misha Brukman17cca962003-11-24 05:28:12 +000061 static const char elfMagic[] = { 0x7f, 'E', 'L', 'F', '\0' };
62 return CheckMagic(FN, elfMagic);
63}
64
Brian Gaeke56be7ff2003-11-11 18:27:21 +000065/// FileOpenable - Returns true IFF Filename names an existing regular
66/// file which we can successfully open.
67///
Chris Lattner2cdd21c2003-12-14 21:35:53 +000068bool llvm::FileOpenable(const std::string &Filename) {
Brian Gaeke56be7ff2003-11-11 18:27:21 +000069 struct stat s;
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 ());
75 if (!FileStream)
76 return false; // File is not openable
77 return true;
78}
79
Chris Lattner7a6ff2b2003-08-01 21:16:14 +000080/// 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
84/// system error.
85///
Chris Lattner2cdd21c2003-12-14 21:35:53 +000086bool llvm::DiffFiles(const std::string &FileA, const std::string &FileB,
87 std::string *Error) {
Chris Lattner7a6ff2b2003-08-01 21:16:14 +000088 std::ifstream FileAStream(FileA.c_str());
89 if (!FileAStream) {
90 if (Error) *Error = "Couldn't open file '" + FileA + "'";
91 return true;
92 }
93
94 std::ifstream FileBStream(FileB.c_str());
95 if (!FileBStream) {
96 if (Error) *Error = "Couldn't open file '" + FileB + "'";
97 return true;
98 }
99
100 // Compare the two files...
101 int C1, C2;
102 do {
103 C1 = FileAStream.get();
104 C2 = FileBStream.get();
105 if (C1 != C2) return true;
106 } while (C1 != EOF);
107
108 return false;
109}
110
111
Chris Lattner5bfac5d2004-06-02 00:52:22 +0000112/// CopyFile - Copy the specified source file to the specified destination,
113/// overwriting destination if it exists. This returns true on failure.
114///
115bool llvm::CopyFile(const std::string &Dest, const std::string &Src) {
116 FDHandle InFD(open(Src.c_str(), O_RDONLY));
117 if (InFD == -1) return true;
118
119 FileRemover FR(Dest);
120
121 FDHandle OutFD(open(Dest.c_str(), O_WRONLY|O_CREAT, 0666));
122 if (OutFD == -1) return true;
123
124 char Buffer[16*1024];
125 while (ssize_t Amt = read(InFD, Buffer, 16*1024)) {
126 if (Amt == -1) {
127 if (errno != EINTR) return true; // Error reading the file.
128 } else {
129 char *BufPtr = Buffer;
130 while (Amt) {
131 ssize_t AmtWritten = write(OutFD, BufPtr, Amt);
132 if (AmtWritten == -1) {
133 if (errno != EINTR) return true; // Error writing the file.
134 } else {
135 Amt -= AmtWritten;
136 BufPtr += AmtWritten;
137 }
138 }
139 }
140 }
141
142 FR.releaseFile(); // Success!
143 return false;
144}
145
146
Chris Lattner7a6ff2b2003-08-01 21:16:14 +0000147/// MoveFileOverIfUpdated - If the file specified by New is different than Old,
148/// or if Old does not exist, move the New file over the Old file. Otherwise,
149/// remove the New file.
150///
Chris Lattner2cdd21c2003-12-14 21:35:53 +0000151void llvm::MoveFileOverIfUpdated(const std::string &New,
152 const std::string &Old) {
Chris Lattner7a6ff2b2003-08-01 21:16:14 +0000153 if (DiffFiles(New, Old)) {
154 if (std::rename(New.c_str(), Old.c_str()))
155 std::cerr << "Error renaming '" << New << "' to '" << Old << "'!\n";
156 } else {
157 std::remove(New.c_str());
158 }
159}
Misha Brukman3d1b0c72003-08-07 21:28:50 +0000160
161/// removeFile - Delete the specified file
162///
Chris Lattner2cdd21c2003-12-14 21:35:53 +0000163void llvm::removeFile(const std::string &Filename) {
Misha Brukman3d1b0c72003-08-07 21:28:50 +0000164 std::remove(Filename.c_str());
165}
166
167/// getUniqueFilename - Return a filename with the specified prefix. If the
168/// file does not exist yet, return it, otherwise add a suffix to make it
169/// unique.
170///
Chris Lattner2cdd21c2003-12-14 21:35:53 +0000171std::string llvm::getUniqueFilename(const std::string &FilenameBase) {
Misha Brukman3d1b0c72003-08-07 21:28:50 +0000172 if (!std::ifstream(FilenameBase.c_str()))
173 return FilenameBase; // Couldn't open the file? Use it!
174
175 // Create a pattern for mkstemp...
176 char *FNBuffer = new char[FilenameBase.size()+8];
177 strcpy(FNBuffer, FilenameBase.c_str());
178 strcpy(FNBuffer+FilenameBase.size(), "-XXXXXX");
179
180 // Agree on a temporary file name to use....
181 int TempFD;
182 if ((TempFD = mkstemp(FNBuffer)) == -1) {
183 std::cerr << "bugpoint: ERROR: Cannot create temporary file in the current "
184 << " directory!\n";
185 exit(1);
186 }
187
Misha Brukman950971d2003-09-16 15:31:46 +0000188 // We don't need to hold the temp file descriptor... we will trust that no one
Misha Brukman3d1b0c72003-08-07 21:28:50 +0000189 // will overwrite/delete the file while we are working on it...
190 close(TempFD);
191 std::string Result(FNBuffer);
192 delete[] FNBuffer;
193 return Result;
194}
John Criswell6991a032003-09-02 20:14:57 +0000195
Brian Gaeke56be7ff2003-11-11 18:27:21 +0000196static bool AddPermissionsBits (const std::string &Filename, mode_t bits) {
197 // Get the umask value from the operating system. We want to use it
198 // when changing the file's permissions. Since calling umask() sets
199 // the umask and returns its old value, we must call it a second
200 // time to reset it to the user's preference.
201 mode_t mask = umask (0777); // The arg. to umask is arbitrary...
John Criswell6991a032003-09-02 20:14:57 +0000202 umask (mask);
203
Brian Gaeke56be7ff2003-11-11 18:27:21 +0000204 // Get the file's current mode.
205 struct stat st;
206 if ((stat (Filename.c_str(), &st)) == -1)
John Criswell6991a032003-09-02 20:14:57 +0000207 return false;
John Criswell6991a032003-09-02 20:14:57 +0000208
Brian Gaeke56be7ff2003-11-11 18:27:21 +0000209 // Change the file to have whichever permissions bits from 'bits'
210 // that the umask would not disable.
211 if ((chmod(Filename.c_str(), (st.st_mode | (bits & ~mask)))) == -1)
John Criswell9adeccc2003-09-02 20:30:16 +0000212 return false;
John Criswell6991a032003-09-02 20:14:57 +0000213
214 return true;
215}
216
Brian Gaeke56be7ff2003-11-11 18:27:21 +0000217/// MakeFileExecutable - Make the file named Filename executable by
218/// setting whichever execute permissions bits the process's current
219/// umask would allow. Filename must name an existing file or
220/// directory. Returns true on success, false on error.
John Criswell66622be2003-09-02 21:09:30 +0000221///
Chris Lattner2cdd21c2003-12-14 21:35:53 +0000222bool llvm::MakeFileExecutable(const std::string &Filename) {
223 return AddPermissionsBits(Filename, 0111);
John Criswell66622be2003-09-02 21:09:30 +0000224}
225
Brian Gaeke56be7ff2003-11-11 18:27:21 +0000226/// MakeFileReadable - Make the file named Filename readable by
227/// setting whichever read permissions bits the process's current
228/// umask would allow. Filename must name an existing file or
229/// directory. Returns true on success, false on error.
230///
Chris Lattner2cdd21c2003-12-14 21:35:53 +0000231bool llvm::MakeFileReadable(const std::string &Filename) {
232 return AddPermissionsBits(Filename, 0444);
Brian Gaeke56be7ff2003-11-11 18:27:21 +0000233}
Chris Lattner2d6481c2003-12-29 21:35:05 +0000234
Chris Lattner316cb082003-12-30 07:36:14 +0000235/// getFileSize - Return the size of the specified file in bytes, or -1 if the
236/// file cannot be read or does not exist.
237long long llvm::getFileSize(const std::string &Filename) {
238 struct stat StatBuf;
239 if (stat(Filename.c_str(), &StatBuf) == -1)
240 return -1;
241 return StatBuf.st_size;
242}
243
Chris Lattner81a085a2003-12-31 06:15:37 +0000244/// getFileTimestamp - Get the last modified time for the specified file in an
245/// unspecified format. This is useful to allow checking to see if a file was
246/// updated since that last time the timestampt was aquired. If the file does
247/// not exist or there is an error getting the time-stamp, zero is returned.
248unsigned long long llvm::getFileTimestamp(const std::string &Filename) {
249 struct stat StatBuf;
250 if (stat(Filename.c_str(), &StatBuf) == -1)
251 return 0;
252 return StatBuf.st_mtime;
253}
254
Chris Lattnereb082992004-05-28 00:23:48 +0000255/// ReadFileIntoAddressSpace - Attempt to map the specific file into the
256/// address space of the current process for reading. If this succeeds,
257/// return the address of the buffer and the length of the file mapped. On
258/// failure, return null.
259void *llvm::ReadFileIntoAddressSpace(const std::string &Filename,
260 unsigned &Length) {
261#ifdef HAVE_MMAP_FILE
262 Length = getFileSize(Filename);
263 if ((int)Length == -1) return 0;
Chris Lattner81a085a2003-12-31 06:15:37 +0000264
Chris Lattnereb082992004-05-28 00:23:48 +0000265 FDHandle FD(open(Filename.c_str(), O_RDONLY));
266 if (FD == -1) return 0;
Chris Lattner81a085a2003-12-31 06:15:37 +0000267
Chris Lattnere53477e2004-05-28 00:34:42 +0000268 // If the file has a length of zero, mmap might return a null pointer. In
269 // this case, allocate a single byte of memory and return it instead.
270 if (Length == 0)
271 return malloc(1);
272
Chris Lattnereb082992004-05-28 00:23:48 +0000273 // mmap in the file all at once...
274 void *Buffer = (void*)mmap(0, Length, PROT_READ, MAP_PRIVATE, FD, 0);
275
276 if (Buffer == (void*)MAP_FAILED)
277 return 0;
Chris Lattnere53477e2004-05-28 00:34:42 +0000278
Chris Lattnereb082992004-05-28 00:23:48 +0000279 return Buffer;
280#else
281 // FIXME: implement with read/write
282 return 0;
283#endif
284}
285
286/// UnmapFileFromAddressSpace - Remove the specified file from the current
287/// address space.
288void llvm::UnmapFileFromAddressSpace(void *Buffer, unsigned Length) {
289#ifdef HAVE_MMAP_FILE
Chris Lattnere53477e2004-05-28 00:34:42 +0000290 if (Length)
291 munmap((char*)Buffer, Length);
292 else
293 free(Buffer); // Zero byte files are malloc(1)'s.
Chris Lattnereb082992004-05-28 00:23:48 +0000294#else
295 free(Buffer);
296#endif
297}
Chris Lattner316cb082003-12-30 07:36:14 +0000298
Chris Lattner2d6481c2003-12-29 21:35:05 +0000299//===----------------------------------------------------------------------===//
300// FDHandle class implementation
301//
302
Chris Lattner9b448b72003-12-29 21:43:58 +0000303FDHandle::~FDHandle() throw() {
Chris Lattner2d6481c2003-12-29 21:35:05 +0000304 if (FD != -1) close(FD);
305}
306
Chris Lattner9b448b72003-12-29 21:43:58 +0000307FDHandle &FDHandle::operator=(int fd) throw() {
Chris Lattner2d6481c2003-12-29 21:35:05 +0000308 if (FD != -1) close(FD);
309 FD = fd;
310 return *this;
311}
312