1 //===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the MemoryBuffer interface. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Support/MemoryBuffer.h" 15 #include "llvm/ADT/OwningPtr.h" 16 #include "llvm/ADT/SmallString.h" 17 #include "llvm/Support/MathExtras.h" 18 #include "llvm/Support/Errno.h" 19 #include "llvm/Support/Path.h" 20 #include "llvm/Support/Process.h" 21 #include "llvm/Support/Program.h" 22 #include "llvm/Support/system_error.h" 23 #include <cassert> 24 #include <cstdio> 25 #include <cstring> 26 #include <cerrno> 27 #include <new> 28 #include <sys/types.h> 29 #include <sys/stat.h> 30 #if !defined(_MSC_VER) && !defined(__MINGW32__) 31 #include <unistd.h> 32 #include <sys/uio.h> 33 #else 34 #include <io.h> 35 #endif 36 #include <fcntl.h> 37 using namespace llvm; 38 39 namespace { const llvm::error_code success; } 40 41 //===----------------------------------------------------------------------===// 42 // MemoryBuffer implementation itself. 43 //===----------------------------------------------------------------------===// 44 45 MemoryBuffer::~MemoryBuffer() { } 46 47 /// init - Initialize this MemoryBuffer as a reference to externally allocated 48 /// memory, memory that we know is already null terminated. 49 void MemoryBuffer::init(const char *BufStart, const char *BufEnd) { 50 assert(BufEnd[0] == 0 && "Buffer is not null terminated!"); 51 BufferStart = BufStart; 52 BufferEnd = BufEnd; 53 } 54 55 //===----------------------------------------------------------------------===// 56 // MemoryBufferMem implementation. 57 //===----------------------------------------------------------------------===// 58 59 /// CopyStringRef - Copies contents of a StringRef into a block of memory and 60 /// null-terminates it. 61 static void CopyStringRef(char *Memory, StringRef Data) { 62 memcpy(Memory, Data.data(), Data.size()); 63 Memory[Data.size()] = 0; // Null terminate string. 64 } 65 66 /// GetNamedBuffer - Allocates a new MemoryBuffer with Name copied after it. 67 template <typename T> 68 static T* GetNamedBuffer(StringRef Buffer, StringRef Name) { 69 char *Mem = static_cast<char*>(operator new(sizeof(T) + Name.size() + 1)); 70 CopyStringRef(Mem + sizeof(T), Name); 71 return new (Mem) T(Buffer); 72 } 73 74 namespace { 75 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory. 76 class MemoryBufferMem : public MemoryBuffer { 77 public: 78 MemoryBufferMem(StringRef InputData) { 79 init(InputData.begin(), InputData.end()); 80 } 81 82 virtual const char *getBufferIdentifier() const { 83 // The name is stored after the class itself. 84 return reinterpret_cast<const char*>(this + 1); 85 } 86 }; 87 } 88 89 /// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note 90 /// that EndPtr[0] must be a null byte and be accessible! 91 MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData, 92 StringRef BufferName) { 93 return GetNamedBuffer<MemoryBufferMem>(InputData, BufferName); 94 } 95 96 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer, 97 /// copying the contents and taking ownership of it. This has no requirements 98 /// on EndPtr[0]. 99 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData, 100 StringRef BufferName) { 101 MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName); 102 if (!Buf) return 0; 103 memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(), 104 InputData.size()); 105 return Buf; 106 } 107 108 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size 109 /// that is not initialized. Note that the caller should initialize the 110 /// memory allocated by this method. The memory is owned by the MemoryBuffer 111 /// object. 112 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size, 113 StringRef BufferName) { 114 // Allocate space for the MemoryBuffer, the data and the name. It is important 115 // that MemoryBuffer and data are aligned so PointerIntPair works with them. 116 size_t AlignedStringLen = 117 RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1, 118 sizeof(void*)); // TODO: Is sizeof(void*) enough? 119 size_t RealLen = AlignedStringLen + Size + 1; 120 char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow)); 121 if (!Mem) return 0; 122 123 // The name is stored after the class itself. 124 CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName); 125 126 // The buffer begins after the name and must be aligned. 127 char *Buf = Mem + AlignedStringLen; 128 Buf[Size] = 0; // Null terminate buffer. 129 130 return new (Mem) MemoryBufferMem(StringRef(Buf, Size)); 131 } 132 133 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that 134 /// is completely initialized to zeros. Note that the caller should 135 /// initialize the memory allocated by this method. The memory is owned by 136 /// the MemoryBuffer object. 137 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) { 138 MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName); 139 if (!SB) return 0; 140 memset(const_cast<char*>(SB->getBufferStart()), 0, Size); 141 return SB; 142 } 143 144 145 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin 146 /// if the Filename is "-". If an error occurs, this returns null and fills 147 /// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN) 148 /// returns an empty buffer. 149 error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename, 150 OwningPtr<MemoryBuffer> &result, 151 int64_t FileSize) { 152 if (Filename == "-") 153 return getSTDIN(result); 154 return getFile(Filename, result, FileSize); 155 } 156 157 error_code MemoryBuffer::getFileOrSTDIN(const char *Filename, 158 OwningPtr<MemoryBuffer> &result, 159 int64_t FileSize) { 160 if (strcmp(Filename, "-") == 0) 161 return getSTDIN(result); 162 return getFile(Filename, result, FileSize); 163 } 164 165 //===----------------------------------------------------------------------===// 166 // MemoryBuffer::getFile implementation. 167 //===----------------------------------------------------------------------===// 168 169 namespace { 170 /// MemoryBufferMMapFile - This represents a file that was mapped in with the 171 /// sys::Path::MapInFilePages method. When destroyed, it calls the 172 /// sys::Path::UnMapFilePages method. 173 class MemoryBufferMMapFile : public MemoryBufferMem { 174 public: 175 MemoryBufferMMapFile(StringRef Buffer) 176 : MemoryBufferMem(Buffer) { } 177 178 ~MemoryBufferMMapFile() { 179 sys::Path::UnMapFilePages(getBufferStart(), getBufferSize()); 180 } 181 }; 182 183 /// FileCloser - RAII object to make sure an FD gets closed properly. 184 class FileCloser { 185 int FD; 186 public: 187 explicit FileCloser(int FD) : FD(FD) {} 188 ~FileCloser() { ::close(FD); } 189 }; 190 } 191 192 error_code MemoryBuffer::getFile(StringRef Filename, 193 OwningPtr<MemoryBuffer> &result, 194 int64_t FileSize) { 195 // Ensure the path is null terminated. 196 SmallString<256> PathBuf(Filename.begin(), Filename.end()); 197 return MemoryBuffer::getFile(PathBuf.c_str(), result, FileSize); 198 } 199 200 error_code MemoryBuffer::getFile(const char *Filename, 201 OwningPtr<MemoryBuffer> &result, 202 int64_t FileSize) { 203 int OpenFlags = O_RDONLY; 204 #ifdef O_BINARY 205 OpenFlags |= O_BINARY; // Open input file in binary mode on win32. 206 #endif 207 int FD = ::open(Filename, OpenFlags); 208 if (FD == -1) { 209 return error_code(errno, posix_category()); 210 } 211 212 return getOpenFile(FD, Filename, result, FileSize); 213 } 214 215 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename, 216 OwningPtr<MemoryBuffer> &result, 217 int64_t FileSize) { 218 FileCloser FC(FD); // Close FD on return. 219 220 // If we don't know the file size, use fstat to find out. fstat on an open 221 // file descriptor is cheaper than stat on a random path. 222 if (FileSize == -1) { 223 struct stat FileInfo; 224 // TODO: This should use fstat64 when available. 225 if (fstat(FD, &FileInfo) == -1) { 226 return error_code(errno, posix_category()); 227 } 228 FileSize = FileInfo.st_size; 229 } 230 231 232 // If the file is large, try to use mmap to read it in. We don't use mmap 233 // for small files, because this can severely fragment our address space. Also 234 // don't try to map files that are exactly a multiple of the system page size, 235 // as the file would not have the required null terminator. 236 // 237 // FIXME: Can we just mmap an extra page in the latter case? 238 if (FileSize >= 4096*4 && 239 (FileSize & (sys::Process::GetPageSize()-1)) != 0) { 240 if (const char *Pages = sys::Path::MapInFilePages(FD, FileSize)) { 241 result.reset(GetNamedBuffer<MemoryBufferMMapFile>( 242 StringRef(Pages, FileSize), Filename)); 243 return success; 244 } 245 } 246 247 MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(FileSize, Filename); 248 if (!Buf) { 249 // Failed to create a buffer. The only way it can fail is if 250 // new(std::nothrow) returns 0. 251 return make_error_code(errc::not_enough_memory); 252 } 253 254 OwningPtr<MemoryBuffer> SB(Buf); 255 char *BufPtr = const_cast<char*>(SB->getBufferStart()); 256 257 size_t BytesLeft = FileSize; 258 while (BytesLeft) { 259 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft); 260 if (NumRead == -1) { 261 if (errno == EINTR) 262 continue; 263 // Error while reading. 264 return error_code(errno, posix_category()); 265 } else if (NumRead == 0) { 266 // We hit EOF early, truncate and terminate buffer. 267 Buf->BufferEnd = BufPtr; 268 *BufPtr = 0; 269 result.swap(SB); 270 return success; 271 } 272 BytesLeft -= NumRead; 273 BufPtr += NumRead; 274 } 275 276 result.swap(SB); 277 return success; 278 } 279 280 //===----------------------------------------------------------------------===// 281 // MemoryBuffer::getSTDIN implementation. 282 //===----------------------------------------------------------------------===// 283 284 error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &result) { 285 // Read in all of the data from stdin, we cannot mmap stdin. 286 // 287 // FIXME: That isn't necessarily true, we should try to mmap stdin and 288 // fallback if it fails. 289 sys::Program::ChangeStdinToBinary(); 290 291 const ssize_t ChunkSize = 4096*4; 292 SmallString<ChunkSize> Buffer; 293 ssize_t ReadBytes; 294 // Read into Buffer until we hit EOF. 295 do { 296 Buffer.reserve(Buffer.size() + ChunkSize); 297 ReadBytes = read(0, Buffer.end(), ChunkSize); 298 if (ReadBytes == -1) { 299 if (errno == EINTR) continue; 300 return error_code(errno, posix_category()); 301 } 302 Buffer.set_size(Buffer.size() + ReadBytes); 303 } while (ReadBytes != 0); 304 305 result.reset(getMemBufferCopy(Buffer, "<stdin>")); 306 return success; 307 } 308