1 //===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the MemoryBuffer interface. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Support/MemoryBuffer.h" 14 #include "llvm/ADT/SmallString.h" 15 #include "llvm/Config/config.h" 16 #include "llvm/Support/AutoConvert.h" 17 #include "llvm/Support/Error.h" 18 #include "llvm/Support/ErrorHandling.h" 19 #include "llvm/Support/Errc.h" 20 #include "llvm/Support/FileSystem.h" 21 #include "llvm/Support/MathExtras.h" 22 #include "llvm/Support/Process.h" 23 #include "llvm/Support/Program.h" 24 #include "llvm/Support/SmallVectorMemoryBuffer.h" 25 #include <cassert> 26 #include <cstring> 27 #include <new> 28 #include <sys/types.h> 29 #include <system_error> 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() = default; 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 if (!Data.empty()) 61 memcpy(Memory, Data.data(), Data.size()); 62 Memory[Data.size()] = 0; // Null terminate string. 63 } 64 65 namespace { 66 struct NamedBufferAlloc { 67 const Twine &Name; 68 NamedBufferAlloc(const Twine &Name) : Name(Name) {} 69 }; 70 } // namespace 71 72 void *operator new(size_t N, const NamedBufferAlloc &Alloc) { 73 SmallString<256> NameBuf; 74 StringRef NameRef = Alloc.Name.toStringRef(NameBuf); 75 76 char *Mem = static_cast<char *>(operator new(N + NameRef.size() + 1)); 77 CopyStringRef(Mem + N, NameRef); 78 return Mem; 79 } 80 81 namespace { 82 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory. 83 template<typename MB> 84 class MemoryBufferMem : public MB { 85 public: 86 MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) { 87 MemoryBuffer::init(InputData.begin(), InputData.end(), 88 RequiresNullTerminator); 89 } 90 91 /// Disable sized deallocation for MemoryBufferMem, because it has 92 /// tail-allocated data. 93 void operator delete(void *p) { ::operator delete(p); } 94 95 StringRef getBufferIdentifier() const override { 96 // The name is stored after the class itself. 97 return StringRef(reinterpret_cast<const char *>(this + 1)); 98 } 99 100 MemoryBuffer::BufferKind getBufferKind() const override { 101 return MemoryBuffer::MemoryBuffer_Malloc; 102 } 103 }; 104 } // namespace 105 106 template <typename MB> 107 static ErrorOr<std::unique_ptr<MB>> 108 getFileAux(const Twine &Filename, uint64_t MapSize, uint64_t Offset, 109 bool IsText, bool RequiresNullTerminator, bool IsVolatile); 110 111 std::unique_ptr<MemoryBuffer> 112 MemoryBuffer::getMemBuffer(StringRef InputData, StringRef BufferName, 113 bool RequiresNullTerminator) { 114 auto *Ret = new (NamedBufferAlloc(BufferName)) 115 MemoryBufferMem<MemoryBuffer>(InputData, RequiresNullTerminator); 116 return std::unique_ptr<MemoryBuffer>(Ret); 117 } 118 119 std::unique_ptr<MemoryBuffer> 120 MemoryBuffer::getMemBuffer(MemoryBufferRef Ref, bool RequiresNullTerminator) { 121 return std::unique_ptr<MemoryBuffer>(getMemBuffer( 122 Ref.getBuffer(), Ref.getBufferIdentifier(), RequiresNullTerminator)); 123 } 124 125 static ErrorOr<std::unique_ptr<WritableMemoryBuffer>> 126 getMemBufferCopyImpl(StringRef InputData, const Twine &BufferName) { 127 auto Buf = WritableMemoryBuffer::getNewUninitMemBuffer(InputData.size(), BufferName); 128 if (!Buf) 129 return make_error_code(errc::not_enough_memory); 130 memcpy(Buf->getBufferStart(), InputData.data(), InputData.size()); 131 return std::move(Buf); 132 } 133 134 std::unique_ptr<MemoryBuffer> 135 MemoryBuffer::getMemBufferCopy(StringRef InputData, const Twine &BufferName) { 136 auto Buf = getMemBufferCopyImpl(InputData, BufferName); 137 if (Buf) 138 return std::move(*Buf); 139 return nullptr; 140 } 141 142 ErrorOr<std::unique_ptr<MemoryBuffer>> 143 MemoryBuffer::getFileOrSTDIN(const Twine &Filename, bool IsText, 144 bool RequiresNullTerminator) { 145 SmallString<256> NameBuf; 146 StringRef NameRef = Filename.toStringRef(NameBuf); 147 148 if (NameRef == "-") 149 return getSTDIN(); 150 return getFile(Filename, IsText, RequiresNullTerminator, 151 /*IsVolatile=*/false); 152 } 153 154 ErrorOr<std::unique_ptr<MemoryBuffer>> 155 MemoryBuffer::getFileSlice(const Twine &FilePath, uint64_t MapSize, 156 uint64_t Offset, bool IsVolatile) { 157 return getFileAux<MemoryBuffer>(FilePath, MapSize, Offset, /*IsText=*/false, 158 /*RequiresNullTerminator=*/false, IsVolatile); 159 } 160 161 //===----------------------------------------------------------------------===// 162 // MemoryBuffer::getFile implementation. 163 //===----------------------------------------------------------------------===// 164 165 namespace { 166 167 template <typename MB> 168 constexpr sys::fs::mapped_file_region::mapmode Mapmode = 169 sys::fs::mapped_file_region::readonly; 170 template <> 171 constexpr sys::fs::mapped_file_region::mapmode Mapmode<MemoryBuffer> = 172 sys::fs::mapped_file_region::readonly; 173 template <> 174 constexpr sys::fs::mapped_file_region::mapmode Mapmode<WritableMemoryBuffer> = 175 sys::fs::mapped_file_region::priv; 176 template <> 177 constexpr sys::fs::mapped_file_region::mapmode 178 Mapmode<WriteThroughMemoryBuffer> = sys::fs::mapped_file_region::readwrite; 179 180 /// Memory maps a file descriptor using sys::fs::mapped_file_region. 181 /// 182 /// This handles converting the offset into a legal offset on the platform. 183 template<typename MB> 184 class MemoryBufferMMapFile : public MB { 185 sys::fs::mapped_file_region MFR; 186 187 static uint64_t getLegalMapOffset(uint64_t Offset) { 188 return Offset & ~(sys::fs::mapped_file_region::alignment() - 1); 189 } 190 191 static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) { 192 return Len + (Offset - getLegalMapOffset(Offset)); 193 } 194 195 const char *getStart(uint64_t Len, uint64_t Offset) { 196 return MFR.const_data() + (Offset - getLegalMapOffset(Offset)); 197 } 198 199 public: 200 MemoryBufferMMapFile(bool RequiresNullTerminator, sys::fs::file_t FD, uint64_t Len, 201 uint64_t Offset, std::error_code &EC) 202 : MFR(FD, Mapmode<MB>, getLegalMapSize(Len, Offset), 203 getLegalMapOffset(Offset), EC) { 204 if (!EC) { 205 const char *Start = getStart(Len, Offset); 206 MemoryBuffer::init(Start, Start + Len, RequiresNullTerminator); 207 } 208 } 209 210 /// Disable sized deallocation for MemoryBufferMMapFile, because it has 211 /// tail-allocated data. 212 void operator delete(void *p) { ::operator delete(p); } 213 214 StringRef getBufferIdentifier() const override { 215 // The name is stored after the class itself. 216 return StringRef(reinterpret_cast<const char *>(this + 1)); 217 } 218 219 MemoryBuffer::BufferKind getBufferKind() const override { 220 return MemoryBuffer::MemoryBuffer_MMap; 221 } 222 223 void dontNeedIfMmap() override { MFR.dontNeed(); } 224 }; 225 } // namespace 226 227 static ErrorOr<std::unique_ptr<WritableMemoryBuffer>> 228 getMemoryBufferForStream(sys::fs::file_t FD, const Twine &BufferName) { 229 SmallString<sys::fs::DefaultReadChunkSize> Buffer; 230 if (Error E = sys::fs::readNativeFileToEOF(FD, Buffer)) 231 return errorToErrorCode(std::move(E)); 232 return getMemBufferCopyImpl(Buffer, BufferName); 233 } 234 235 ErrorOr<std::unique_ptr<MemoryBuffer>> 236 MemoryBuffer::getFile(const Twine &Filename, bool IsText, 237 bool RequiresNullTerminator, bool IsVolatile) { 238 return getFileAux<MemoryBuffer>(Filename, /*MapSize=*/-1, /*Offset=*/0, 239 IsText, RequiresNullTerminator, IsVolatile); 240 } 241 242 template <typename MB> 243 static ErrorOr<std::unique_ptr<MB>> 244 getOpenFileImpl(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize, 245 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator, 246 bool IsVolatile); 247 248 template <typename MB> 249 static ErrorOr<std::unique_ptr<MB>> 250 getFileAux(const Twine &Filename, uint64_t MapSize, uint64_t Offset, 251 bool IsText, bool RequiresNullTerminator, bool IsVolatile) { 252 Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForRead( 253 Filename, IsText ? sys::fs::OF_TextWithCRLF : sys::fs::OF_None); 254 if (!FDOrErr) 255 return errorToErrorCode(FDOrErr.takeError()); 256 sys::fs::file_t FD = *FDOrErr; 257 auto Ret = getOpenFileImpl<MB>(FD, Filename, /*FileSize=*/-1, MapSize, Offset, 258 RequiresNullTerminator, IsVolatile); 259 sys::fs::closeFile(FD); 260 return Ret; 261 } 262 263 ErrorOr<std::unique_ptr<WritableMemoryBuffer>> 264 WritableMemoryBuffer::getFile(const Twine &Filename, bool IsVolatile) { 265 return getFileAux<WritableMemoryBuffer>( 266 Filename, /*MapSize=*/-1, /*Offset=*/0, /*IsText=*/false, 267 /*RequiresNullTerminator=*/false, IsVolatile); 268 } 269 270 ErrorOr<std::unique_ptr<WritableMemoryBuffer>> 271 WritableMemoryBuffer::getFileSlice(const Twine &Filename, uint64_t MapSize, 272 uint64_t Offset, bool IsVolatile) { 273 return getFileAux<WritableMemoryBuffer>( 274 Filename, MapSize, Offset, /*IsText=*/false, 275 /*RequiresNullTerminator=*/false, IsVolatile); 276 } 277 278 std::unique_ptr<WritableMemoryBuffer> 279 WritableMemoryBuffer::getNewUninitMemBuffer(size_t Size, const Twine &BufferName) { 280 using MemBuffer = MemoryBufferMem<WritableMemoryBuffer>; 281 // Allocate space for the MemoryBuffer, the data and the name. It is important 282 // that MemoryBuffer and data are aligned so PointerIntPair works with them. 283 // TODO: Is 16-byte alignment enough? We copy small object files with large 284 // alignment expectations into this buffer. 285 SmallString<256> NameBuf; 286 StringRef NameRef = BufferName.toStringRef(NameBuf); 287 size_t AlignedStringLen = alignTo(sizeof(MemBuffer) + NameRef.size() + 1, 16); 288 size_t RealLen = AlignedStringLen + Size + 1; 289 if (RealLen <= Size) // Check for rollover. 290 return nullptr; 291 char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow)); 292 if (!Mem) 293 return nullptr; 294 295 // The name is stored after the class itself. 296 CopyStringRef(Mem + sizeof(MemBuffer), NameRef); 297 298 // The buffer begins after the name and must be aligned. 299 char *Buf = Mem + AlignedStringLen; 300 Buf[Size] = 0; // Null terminate buffer. 301 302 auto *Ret = new (Mem) MemBuffer(StringRef(Buf, Size), true); 303 return std::unique_ptr<WritableMemoryBuffer>(Ret); 304 } 305 306 std::unique_ptr<WritableMemoryBuffer> 307 WritableMemoryBuffer::getNewMemBuffer(size_t Size, const Twine &BufferName) { 308 auto SB = WritableMemoryBuffer::getNewUninitMemBuffer(Size, BufferName); 309 if (!SB) 310 return nullptr; 311 memset(SB->getBufferStart(), 0, Size); 312 return SB; 313 } 314 315 static bool shouldUseMmap(sys::fs::file_t FD, 316 size_t FileSize, 317 size_t MapSize, 318 off_t Offset, 319 bool RequiresNullTerminator, 320 int PageSize, 321 bool IsVolatile) { 322 // mmap may leave the buffer without null terminator if the file size changed 323 // by the time the last page is mapped in, so avoid it if the file size is 324 // likely to change. 325 if (IsVolatile && RequiresNullTerminator) 326 return false; 327 328 // We don't use mmap for small files because this can severely fragment our 329 // address space. 330 if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize) 331 return false; 332 333 if (!RequiresNullTerminator) 334 return true; 335 336 // If we don't know the file size, use fstat to find out. fstat on an open 337 // file descriptor is cheaper than stat on a random path. 338 // FIXME: this chunk of code is duplicated, but it avoids a fstat when 339 // RequiresNullTerminator = false and MapSize != -1. 340 if (FileSize == size_t(-1)) { 341 sys::fs::file_status Status; 342 if (sys::fs::status(FD, Status)) 343 return false; 344 FileSize = Status.getSize(); 345 } 346 347 // If we need a null terminator and the end of the map is inside the file, 348 // we cannot use mmap. 349 size_t End = Offset + MapSize; 350 assert(End <= FileSize); 351 if (End != FileSize) 352 return false; 353 354 // Don't try to map files that are exactly a multiple of the system page size 355 // if we need a null terminator. 356 if ((FileSize & (PageSize -1)) == 0) 357 return false; 358 359 #if defined(__CYGWIN__) 360 // Don't try to map files that are exactly a multiple of the physical page size 361 // if we need a null terminator. 362 // FIXME: We should reorganize again getPageSize() on Win32. 363 if ((FileSize & (4096 - 1)) == 0) 364 return false; 365 #endif 366 367 return true; 368 } 369 370 static ErrorOr<std::unique_ptr<WriteThroughMemoryBuffer>> 371 getReadWriteFile(const Twine &Filename, uint64_t FileSize, uint64_t MapSize, 372 uint64_t Offset) { 373 Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForReadWrite( 374 Filename, sys::fs::CD_OpenExisting, sys::fs::OF_None); 375 if (!FDOrErr) 376 return errorToErrorCode(FDOrErr.takeError()); 377 sys::fs::file_t FD = *FDOrErr; 378 379 // Default is to map the full file. 380 if (MapSize == uint64_t(-1)) { 381 // If we don't know the file size, use fstat to find out. fstat on an open 382 // file descriptor is cheaper than stat on a random path. 383 if (FileSize == uint64_t(-1)) { 384 sys::fs::file_status Status; 385 std::error_code EC = sys::fs::status(FD, Status); 386 if (EC) 387 return EC; 388 389 // If this not a file or a block device (e.g. it's a named pipe 390 // or character device), we can't mmap it, so error out. 391 sys::fs::file_type Type = Status.type(); 392 if (Type != sys::fs::file_type::regular_file && 393 Type != sys::fs::file_type::block_file) 394 return make_error_code(errc::invalid_argument); 395 396 FileSize = Status.getSize(); 397 } 398 MapSize = FileSize; 399 } 400 401 std::error_code EC; 402 std::unique_ptr<WriteThroughMemoryBuffer> Result( 403 new (NamedBufferAlloc(Filename)) 404 MemoryBufferMMapFile<WriteThroughMemoryBuffer>(false, FD, MapSize, 405 Offset, EC)); 406 if (EC) 407 return EC; 408 return std::move(Result); 409 } 410 411 ErrorOr<std::unique_ptr<WriteThroughMemoryBuffer>> 412 WriteThroughMemoryBuffer::getFile(const Twine &Filename, int64_t FileSize) { 413 return getReadWriteFile(Filename, FileSize, FileSize, 0); 414 } 415 416 /// Map a subrange of the specified file as a WritableMemoryBuffer. 417 ErrorOr<std::unique_ptr<WriteThroughMemoryBuffer>> 418 WriteThroughMemoryBuffer::getFileSlice(const Twine &Filename, uint64_t MapSize, 419 uint64_t Offset) { 420 return getReadWriteFile(Filename, -1, MapSize, Offset); 421 } 422 423 template <typename MB> 424 static ErrorOr<std::unique_ptr<MB>> 425 getOpenFileImpl(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize, 426 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator, 427 bool IsVolatile) { 428 static int PageSize = sys::Process::getPageSizeEstimate(); 429 430 // Default is to map the full file. 431 if (MapSize == uint64_t(-1)) { 432 // If we don't know the file size, use fstat to find out. fstat on an open 433 // file descriptor is cheaper than stat on a random path. 434 if (FileSize == uint64_t(-1)) { 435 sys::fs::file_status Status; 436 std::error_code EC = sys::fs::status(FD, Status); 437 if (EC) 438 return EC; 439 440 // If this not a file or a block device (e.g. it's a named pipe 441 // or character device), we can't trust the size. Create the memory 442 // buffer by copying off the stream. 443 sys::fs::file_type Type = Status.type(); 444 if (Type != sys::fs::file_type::regular_file && 445 Type != sys::fs::file_type::block_file) 446 return getMemoryBufferForStream(FD, Filename); 447 448 FileSize = Status.getSize(); 449 } 450 MapSize = FileSize; 451 } 452 453 if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator, 454 PageSize, IsVolatile)) { 455 std::error_code EC; 456 std::unique_ptr<MB> Result( 457 new (NamedBufferAlloc(Filename)) MemoryBufferMMapFile<MB>( 458 RequiresNullTerminator, FD, MapSize, Offset, EC)); 459 if (!EC) 460 return std::move(Result); 461 } 462 463 #ifdef __MVS__ 464 // Set codepage auto-conversion for z/OS. 465 if (auto EC = llvm::enableAutoConversion(FD)) 466 return EC; 467 #endif 468 469 auto Buf = WritableMemoryBuffer::getNewUninitMemBuffer(MapSize, Filename); 470 if (!Buf) { 471 // Failed to create a buffer. The only way it can fail is if 472 // new(std::nothrow) returns 0. 473 return make_error_code(errc::not_enough_memory); 474 } 475 476 // Read until EOF, zero-initialize the rest. 477 MutableArrayRef<char> ToRead = Buf->getBuffer(); 478 while (!ToRead.empty()) { 479 Expected<size_t> ReadBytes = 480 sys::fs::readNativeFileSlice(FD, ToRead, Offset); 481 if (!ReadBytes) 482 return errorToErrorCode(ReadBytes.takeError()); 483 if (*ReadBytes == 0) { 484 std::memset(ToRead.data(), 0, ToRead.size()); 485 break; 486 } 487 ToRead = ToRead.drop_front(*ReadBytes); 488 Offset += *ReadBytes; 489 } 490 491 return std::move(Buf); 492 } 493 494 ErrorOr<std::unique_ptr<MemoryBuffer>> 495 MemoryBuffer::getOpenFile(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize, 496 bool RequiresNullTerminator, bool IsVolatile) { 497 return getOpenFileImpl<MemoryBuffer>(FD, Filename, FileSize, FileSize, 0, 498 RequiresNullTerminator, IsVolatile); 499 } 500 501 ErrorOr<std::unique_ptr<MemoryBuffer>> 502 MemoryBuffer::getOpenFileSlice(sys::fs::file_t FD, const Twine &Filename, uint64_t MapSize, 503 int64_t Offset, bool IsVolatile) { 504 assert(MapSize != uint64_t(-1)); 505 return getOpenFileImpl<MemoryBuffer>(FD, Filename, -1, MapSize, Offset, false, 506 IsVolatile); 507 } 508 509 ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getSTDIN() { 510 // Read in all of the data from stdin, we cannot mmap stdin. 511 // 512 // FIXME: That isn't necessarily true, we should try to mmap stdin and 513 // fallback if it fails. 514 sys::ChangeStdinMode(sys::fs::OF_Text); 515 516 return getMemoryBufferForStream(sys::fs::getStdinHandle(), "<stdin>"); 517 } 518 519 ErrorOr<std::unique_ptr<MemoryBuffer>> 520 MemoryBuffer::getFileAsStream(const Twine &Filename) { 521 Expected<sys::fs::file_t> FDOrErr = 522 sys::fs::openNativeFileForRead(Filename, sys::fs::OF_None); 523 if (!FDOrErr) 524 return errorToErrorCode(FDOrErr.takeError()); 525 sys::fs::file_t FD = *FDOrErr; 526 ErrorOr<std::unique_ptr<MemoryBuffer>> Ret = 527 getMemoryBufferForStream(FD, Filename); 528 sys::fs::closeFile(FD); 529 return Ret; 530 } 531 532 MemoryBufferRef MemoryBuffer::getMemBufferRef() const { 533 StringRef Data = getBuffer(); 534 StringRef Identifier = getBufferIdentifier(); 535 return MemoryBufferRef(Data, Identifier); 536 } 537 538 SmallVectorMemoryBuffer::~SmallVectorMemoryBuffer() = default; 539