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/SmallString.h" 16 #include "llvm/Config/config.h" 17 #include "llvm/Support/Errc.h" 18 #include "llvm/Support/Errno.h" 19 #include "llvm/Support/FileSystem.h" 20 #include "llvm/Support/MathExtras.h" 21 #include "llvm/Support/Path.h" 22 #include "llvm/Support/Process.h" 23 #include "llvm/Support/Program.h" 24 #include <cassert> 25 #include <cerrno> 26 #include <cstdio> 27 #include <cstring> 28 #include <new> 29 #include <sys/types.h> 30 #include <system_error> 31 #if !defined(_MSC_VER) && !defined(__MINGW32__) 32 #include <unistd.h> 33 #else 34 #include <io.h> 35 #endif 36 using namespace llvm; 37 38 //===----------------------------------------------------------------------===// 39 // MemoryBuffer implementation itself. 40 //===----------------------------------------------------------------------===// 41 42 MemoryBuffer::~MemoryBuffer() { } 43 44 /// init - Initialize this MemoryBuffer as a reference to externally allocated 45 /// memory, memory that we know is already null terminated. 46 void MemoryBuffer::init(const char *BufStart, const char *BufEnd, 47 bool RequiresNullTerminator) { 48 assert((!RequiresNullTerminator || BufEnd[0] == 0) && 49 "Buffer is not null terminated!"); 50 BufferStart = BufStart; 51 BufferEnd = BufEnd; 52 } 53 54 //===----------------------------------------------------------------------===// 55 // MemoryBufferMem implementation. 56 //===----------------------------------------------------------------------===// 57 58 /// CopyStringRef - Copies contents of a StringRef into a block of memory and 59 /// null-terminates it. 60 static void CopyStringRef(char *Memory, StringRef Data) { 61 memcpy(Memory, Data.data(), Data.size()); 62 Memory[Data.size()] = 0; // Null terminate string. 63 } 64 65 namespace { 66 struct NamedBufferAlloc { 67 StringRef Name; 68 NamedBufferAlloc(StringRef Name) : Name(Name) {} 69 }; 70 } 71 72 void *operator new(size_t N, const NamedBufferAlloc &Alloc) { 73 char *Mem = static_cast<char *>(operator new(N + Alloc.Name.size() + 1)); 74 CopyStringRef(Mem + N, Alloc.Name); 75 return Mem; 76 } 77 78 namespace { 79 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory. 80 class MemoryBufferMem : public MemoryBuffer { 81 public: 82 MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) { 83 init(InputData.begin(), InputData.end(), RequiresNullTerminator); 84 } 85 86 const char *getBufferIdentifier() const override { 87 // The name is stored after the class itself. 88 return reinterpret_cast<const char*>(this + 1); 89 } 90 91 BufferKind getBufferKind() const override { 92 return MemoryBuffer_Malloc; 93 } 94 }; 95 } 96 97 /// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note 98 /// that InputData must be a null terminated if RequiresNullTerminator is true! 99 MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData, 100 StringRef BufferName, 101 bool RequiresNullTerminator) { 102 return new (NamedBufferAlloc(BufferName)) 103 MemoryBufferMem(InputData, RequiresNullTerminator); 104 } 105 106 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer, 107 /// copying the contents and taking ownership of it. This has no requirements 108 /// on EndPtr[0]. 109 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData, 110 StringRef BufferName) { 111 MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName); 112 if (!Buf) return nullptr; 113 memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(), 114 InputData.size()); 115 return Buf; 116 } 117 118 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size 119 /// that is not initialized. Note that the caller should initialize the 120 /// memory allocated by this method. The memory is owned by the MemoryBuffer 121 /// object. 122 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size, 123 StringRef BufferName) { 124 // Allocate space for the MemoryBuffer, the data and the name. It is important 125 // that MemoryBuffer and data are aligned so PointerIntPair works with them. 126 // TODO: Is 16-byte alignment enough? We copy small object files with large 127 // alignment expectations into this buffer. 128 size_t AlignedStringLen = 129 RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1, 16); 130 size_t RealLen = AlignedStringLen + Size + 1; 131 char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow)); 132 if (!Mem) return nullptr; 133 134 // The name is stored after the class itself. 135 CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName); 136 137 // The buffer begins after the name and must be aligned. 138 char *Buf = Mem + AlignedStringLen; 139 Buf[Size] = 0; // Null terminate buffer. 140 141 return new (Mem) MemoryBufferMem(StringRef(Buf, Size), true); 142 } 143 144 /// getNewMemBuffer - Allocate a new zero-initialized MemoryBuffer of the 145 /// specified size. Note that the caller need not initialize the memory 146 /// allocated by this method. The memory is owned by the MemoryBuffer object. 147 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) { 148 MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName); 149 if (!SB) return nullptr; 150 memset(const_cast<char*>(SB->getBufferStart()), 0, Size); 151 return SB; 152 } 153 154 ErrorOr<std::unique_ptr<MemoryBuffer>> 155 MemoryBuffer::getFileOrSTDIN(StringRef Filename, int64_t FileSize) { 156 if (Filename == "-") 157 return getSTDIN(); 158 return getFile(Filename, FileSize); 159 } 160 161 162 //===----------------------------------------------------------------------===// 163 // MemoryBuffer::getFile implementation. 164 //===----------------------------------------------------------------------===// 165 166 namespace { 167 /// \brief Memory maps a file descriptor using sys::fs::mapped_file_region. 168 /// 169 /// This handles converting the offset into a legal offset on the platform. 170 class MemoryBufferMMapFile : public MemoryBuffer { 171 sys::fs::mapped_file_region MFR; 172 173 static uint64_t getLegalMapOffset(uint64_t Offset) { 174 return Offset & ~(sys::fs::mapped_file_region::alignment() - 1); 175 } 176 177 static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) { 178 return Len + (Offset - getLegalMapOffset(Offset)); 179 } 180 181 const char *getStart(uint64_t Len, uint64_t Offset) { 182 return MFR.const_data() + (Offset - getLegalMapOffset(Offset)); 183 } 184 185 public: 186 MemoryBufferMMapFile(bool RequiresNullTerminator, int FD, uint64_t Len, 187 uint64_t Offset, std::error_code EC) 188 : MFR(FD, false, sys::fs::mapped_file_region::readonly, 189 getLegalMapSize(Len, Offset), getLegalMapOffset(Offset), EC) { 190 if (!EC) { 191 const char *Start = getStart(Len, Offset); 192 init(Start, Start + Len, RequiresNullTerminator); 193 } 194 } 195 196 const char *getBufferIdentifier() const override { 197 // The name is stored after the class itself. 198 return reinterpret_cast<const char *>(this + 1); 199 } 200 201 BufferKind getBufferKind() const override { 202 return MemoryBuffer_MMap; 203 } 204 }; 205 } 206 207 static ErrorOr<std::unique_ptr<MemoryBuffer>> 208 getMemoryBufferForStream(int FD, StringRef BufferName) { 209 const ssize_t ChunkSize = 4096*4; 210 SmallString<ChunkSize> Buffer; 211 ssize_t ReadBytes; 212 // Read into Buffer until we hit EOF. 213 do { 214 Buffer.reserve(Buffer.size() + ChunkSize); 215 ReadBytes = read(FD, Buffer.end(), ChunkSize); 216 if (ReadBytes == -1) { 217 if (errno == EINTR) continue; 218 return std::error_code(errno, std::generic_category()); 219 } 220 Buffer.set_size(Buffer.size() + ReadBytes); 221 } while (ReadBytes != 0); 222 223 std::unique_ptr<MemoryBuffer> Ret( 224 MemoryBuffer::getMemBufferCopy(Buffer, BufferName)); 225 return std::move(Ret); 226 } 227 228 static ErrorOr<std::unique_ptr<MemoryBuffer>> 229 getFileAux(const char *Filename, int64_t FileSize, bool RequiresNullTerminator, 230 bool IsVolatileSize); 231 232 ErrorOr<std::unique_ptr<MemoryBuffer>> 233 MemoryBuffer::getFile(Twine Filename, int64_t FileSize, 234 bool RequiresNullTerminator, bool IsVolatileSize) { 235 // Ensure the path is null terminated. 236 SmallString<256> PathBuf; 237 StringRef NullTerminatedName = Filename.toNullTerminatedStringRef(PathBuf); 238 return getFileAux(NullTerminatedName.data(), FileSize, RequiresNullTerminator, 239 IsVolatileSize); 240 } 241 242 static ErrorOr<std::unique_ptr<MemoryBuffer>> 243 getOpenFileImpl(int FD, const char *Filename, uint64_t FileSize, 244 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator, 245 bool IsVolatileSize); 246 247 static ErrorOr<std::unique_ptr<MemoryBuffer>> 248 getFileAux(const char *Filename, int64_t FileSize, bool RequiresNullTerminator, 249 bool IsVolatileSize) { 250 int FD; 251 std::error_code EC = sys::fs::openFileForRead(Filename, FD); 252 if (EC) 253 return EC; 254 255 ErrorOr<std::unique_ptr<MemoryBuffer>> Ret = 256 getOpenFileImpl(FD, Filename, FileSize, FileSize, 0, 257 RequiresNullTerminator, IsVolatileSize); 258 close(FD); 259 return Ret; 260 } 261 262 static bool shouldUseMmap(int FD, 263 size_t FileSize, 264 size_t MapSize, 265 off_t Offset, 266 bool RequiresNullTerminator, 267 int PageSize, 268 bool IsVolatileSize) { 269 // mmap may leave the buffer without null terminator if the file size changed 270 // by the time the last page is mapped in, so avoid it if the file size is 271 // likely to change. 272 if (IsVolatileSize) 273 return false; 274 275 // We don't use mmap for small files because this can severely fragment our 276 // address space. 277 if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize) 278 return false; 279 280 if (!RequiresNullTerminator) 281 return true; 282 283 284 // If we don't know the file size, use fstat to find out. fstat on an open 285 // file descriptor is cheaper than stat on a random path. 286 // FIXME: this chunk of code is duplicated, but it avoids a fstat when 287 // RequiresNullTerminator = false and MapSize != -1. 288 if (FileSize == size_t(-1)) { 289 sys::fs::file_status Status; 290 if (sys::fs::status(FD, Status)) 291 return false; 292 FileSize = Status.getSize(); 293 } 294 295 // If we need a null terminator and the end of the map is inside the file, 296 // we cannot use mmap. 297 size_t End = Offset + MapSize; 298 assert(End <= FileSize); 299 if (End != FileSize) 300 return false; 301 302 // Don't try to map files that are exactly a multiple of the system page size 303 // if we need a null terminator. 304 if ((FileSize & (PageSize -1)) == 0) 305 return false; 306 307 #if defined(__CYGWIN__) 308 // Don't try to map files that are exactly a multiple of the physical page size 309 // if we need a null terminator. 310 // FIXME: We should reorganize again getPageSize() on Win32. 311 if ((FileSize & (4096 - 1)) == 0) 312 return false; 313 #endif 314 315 return true; 316 } 317 318 static ErrorOr<std::unique_ptr<MemoryBuffer>> 319 getOpenFileImpl(int FD, const char *Filename, uint64_t FileSize, 320 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator, 321 bool IsVolatileSize) { 322 static int PageSize = sys::process::get_self()->page_size(); 323 324 // Default is to map the full file. 325 if (MapSize == uint64_t(-1)) { 326 // If we don't know the file size, use fstat to find out. fstat on an open 327 // file descriptor is cheaper than stat on a random path. 328 if (FileSize == uint64_t(-1)) { 329 sys::fs::file_status Status; 330 std::error_code EC = sys::fs::status(FD, Status); 331 if (EC) 332 return EC; 333 334 // If this not a file or a block device (e.g. it's a named pipe 335 // or character device), we can't trust the size. Create the memory 336 // buffer by copying off the stream. 337 sys::fs::file_type Type = Status.type(); 338 if (Type != sys::fs::file_type::regular_file && 339 Type != sys::fs::file_type::block_file) 340 return getMemoryBufferForStream(FD, Filename); 341 342 FileSize = Status.getSize(); 343 } 344 MapSize = FileSize; 345 } 346 347 if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator, 348 PageSize, IsVolatileSize)) { 349 std::error_code EC; 350 std::unique_ptr<MemoryBuffer> Result( 351 new (NamedBufferAlloc(Filename)) 352 MemoryBufferMMapFile(RequiresNullTerminator, FD, MapSize, Offset, EC)); 353 if (!EC) 354 return std::move(Result); 355 } 356 357 MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename); 358 if (!Buf) { 359 // Failed to create a buffer. The only way it can fail is if 360 // new(std::nothrow) returns 0. 361 return make_error_code(errc::not_enough_memory); 362 } 363 364 std::unique_ptr<MemoryBuffer> SB(Buf); 365 char *BufPtr = const_cast<char*>(SB->getBufferStart()); 366 367 size_t BytesLeft = MapSize; 368 #ifndef HAVE_PREAD 369 if (lseek(FD, Offset, SEEK_SET) == -1) 370 return std::error_code(errno, std::generic_category()); 371 #endif 372 373 while (BytesLeft) { 374 #ifdef HAVE_PREAD 375 ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset); 376 #else 377 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft); 378 #endif 379 if (NumRead == -1) { 380 if (errno == EINTR) 381 continue; 382 // Error while reading. 383 return std::error_code(errno, std::generic_category()); 384 } 385 if (NumRead == 0) { 386 memset(BufPtr, 0, BytesLeft); // zero-initialize rest of the buffer. 387 break; 388 } 389 BytesLeft -= NumRead; 390 BufPtr += NumRead; 391 } 392 393 return std::move(SB); 394 } 395 396 ErrorOr<std::unique_ptr<MemoryBuffer>> 397 MemoryBuffer::getOpenFile(int FD, const char *Filename, uint64_t FileSize, 398 bool RequiresNullTerminator, bool IsVolatileSize) { 399 return getOpenFileImpl(FD, Filename, FileSize, FileSize, 0, 400 RequiresNullTerminator, IsVolatileSize); 401 } 402 403 ErrorOr<std::unique_ptr<MemoryBuffer>> 404 MemoryBuffer::getOpenFileSlice(int FD, const char *Filename, uint64_t MapSize, 405 int64_t Offset, bool IsVolatileSize) { 406 return getOpenFileImpl(FD, Filename, -1, MapSize, Offset, false, 407 IsVolatileSize); 408 } 409 410 ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getSTDIN() { 411 // Read in all of the data from stdin, we cannot mmap stdin. 412 // 413 // FIXME: That isn't necessarily true, we should try to mmap stdin and 414 // fallback if it fails. 415 sys::ChangeStdinToBinary(); 416 417 return getMemoryBufferForStream(0, "<stdin>"); 418 } 419 420 MemoryBufferRef MemoryBuffer::getMemBufferRef() const { 421 StringRef Data = getBuffer(); 422 StringRef Identifier = getBufferIdentifier(); 423 return MemoryBufferRef(Data, Identifier); 424 } 425