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