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() { } 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 char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow)); 290 if (!Mem) 291 return nullptr; 292 293 // The name is stored after the class itself. 294 CopyStringRef(Mem + sizeof(MemBuffer), NameRef); 295 296 // The buffer begins after the name and must be aligned. 297 char *Buf = Mem + AlignedStringLen; 298 Buf[Size] = 0; // Null terminate buffer. 299 300 auto *Ret = new (Mem) MemBuffer(StringRef(Buf, Size), true); 301 return std::unique_ptr<WritableMemoryBuffer>(Ret); 302 } 303 304 std::unique_ptr<WritableMemoryBuffer> 305 WritableMemoryBuffer::getNewMemBuffer(size_t Size, const Twine &BufferName) { 306 auto SB = WritableMemoryBuffer::getNewUninitMemBuffer(Size, BufferName); 307 if (!SB) 308 return nullptr; 309 memset(SB->getBufferStart(), 0, Size); 310 return SB; 311 } 312 313 static bool shouldUseMmap(sys::fs::file_t FD, 314 size_t FileSize, 315 size_t MapSize, 316 off_t Offset, 317 bool RequiresNullTerminator, 318 int PageSize, 319 bool IsVolatile) { 320 // mmap may leave the buffer without null terminator if the file size changed 321 // by the time the last page is mapped in, so avoid it if the file size is 322 // likely to change. 323 if (IsVolatile && RequiresNullTerminator) 324 return false; 325 326 // We don't use mmap for small files because this can severely fragment our 327 // address space. 328 if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize) 329 return false; 330 331 if (!RequiresNullTerminator) 332 return true; 333 334 // If we don't know the file size, use fstat to find out. fstat on an open 335 // file descriptor is cheaper than stat on a random path. 336 // FIXME: this chunk of code is duplicated, but it avoids a fstat when 337 // RequiresNullTerminator = false and MapSize != -1. 338 if (FileSize == size_t(-1)) { 339 sys::fs::file_status Status; 340 if (sys::fs::status(FD, Status)) 341 return false; 342 FileSize = Status.getSize(); 343 } 344 345 // If we need a null terminator and the end of the map is inside the file, 346 // we cannot use mmap. 347 size_t End = Offset + MapSize; 348 assert(End <= FileSize); 349 if (End != FileSize) 350 return false; 351 352 // Don't try to map files that are exactly a multiple of the system page size 353 // if we need a null terminator. 354 if ((FileSize & (PageSize -1)) == 0) 355 return false; 356 357 #if defined(__CYGWIN__) 358 // Don't try to map files that are exactly a multiple of the physical page size 359 // if we need a null terminator. 360 // FIXME: We should reorganize again getPageSize() on Win32. 361 if ((FileSize & (4096 - 1)) == 0) 362 return false; 363 #endif 364 365 return true; 366 } 367 368 static ErrorOr<std::unique_ptr<WriteThroughMemoryBuffer>> 369 getReadWriteFile(const Twine &Filename, uint64_t FileSize, uint64_t MapSize, 370 uint64_t Offset) { 371 Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForReadWrite( 372 Filename, sys::fs::CD_OpenExisting, sys::fs::OF_None); 373 if (!FDOrErr) 374 return errorToErrorCode(FDOrErr.takeError()); 375 sys::fs::file_t FD = *FDOrErr; 376 377 // Default is to map the full file. 378 if (MapSize == uint64_t(-1)) { 379 // If we don't know the file size, use fstat to find out. fstat on an open 380 // file descriptor is cheaper than stat on a random path. 381 if (FileSize == uint64_t(-1)) { 382 sys::fs::file_status Status; 383 std::error_code EC = sys::fs::status(FD, Status); 384 if (EC) 385 return EC; 386 387 // If this not a file or a block device (e.g. it's a named pipe 388 // or character device), we can't mmap it, so error out. 389 sys::fs::file_type Type = Status.type(); 390 if (Type != sys::fs::file_type::regular_file && 391 Type != sys::fs::file_type::block_file) 392 return make_error_code(errc::invalid_argument); 393 394 FileSize = Status.getSize(); 395 } 396 MapSize = FileSize; 397 } 398 399 std::error_code EC; 400 std::unique_ptr<WriteThroughMemoryBuffer> Result( 401 new (NamedBufferAlloc(Filename)) 402 MemoryBufferMMapFile<WriteThroughMemoryBuffer>(false, FD, MapSize, 403 Offset, EC)); 404 if (EC) 405 return EC; 406 return std::move(Result); 407 } 408 409 ErrorOr<std::unique_ptr<WriteThroughMemoryBuffer>> 410 WriteThroughMemoryBuffer::getFile(const Twine &Filename, int64_t FileSize) { 411 return getReadWriteFile(Filename, FileSize, FileSize, 0); 412 } 413 414 /// Map a subrange of the specified file as a WritableMemoryBuffer. 415 ErrorOr<std::unique_ptr<WriteThroughMemoryBuffer>> 416 WriteThroughMemoryBuffer::getFileSlice(const Twine &Filename, uint64_t MapSize, 417 uint64_t Offset) { 418 return getReadWriteFile(Filename, -1, MapSize, Offset); 419 } 420 421 template <typename MB> 422 static ErrorOr<std::unique_ptr<MB>> 423 getOpenFileImpl(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize, 424 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator, 425 bool IsVolatile) { 426 static int PageSize = sys::Process::getPageSizeEstimate(); 427 428 // Default is to map the full file. 429 if (MapSize == uint64_t(-1)) { 430 // If we don't know the file size, use fstat to find out. fstat on an open 431 // file descriptor is cheaper than stat on a random path. 432 if (FileSize == uint64_t(-1)) { 433 sys::fs::file_status Status; 434 std::error_code EC = sys::fs::status(FD, Status); 435 if (EC) 436 return EC; 437 438 // If this not a file or a block device (e.g. it's a named pipe 439 // or character device), we can't trust the size. Create the memory 440 // buffer by copying off the stream. 441 sys::fs::file_type Type = Status.type(); 442 if (Type != sys::fs::file_type::regular_file && 443 Type != sys::fs::file_type::block_file) 444 return getMemoryBufferForStream(FD, Filename); 445 446 FileSize = Status.getSize(); 447 } 448 MapSize = FileSize; 449 } 450 451 if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator, 452 PageSize, IsVolatile)) { 453 std::error_code EC; 454 std::unique_ptr<MB> Result( 455 new (NamedBufferAlloc(Filename)) MemoryBufferMMapFile<MB>( 456 RequiresNullTerminator, FD, MapSize, Offset, EC)); 457 if (!EC) 458 return std::move(Result); 459 } 460 461 #ifdef __MVS__ 462 // Set codepage auto-conversion for z/OS. 463 if (auto EC = llvm::enableAutoConversion(FD)) 464 return EC; 465 #endif 466 467 auto Buf = WritableMemoryBuffer::getNewUninitMemBuffer(MapSize, Filename); 468 if (!Buf) { 469 // Failed to create a buffer. The only way it can fail is if 470 // new(std::nothrow) returns 0. 471 return make_error_code(errc::not_enough_memory); 472 } 473 474 // Read until EOF, zero-initialize the rest. 475 MutableArrayRef<char> ToRead = Buf->getBuffer(); 476 while (!ToRead.empty()) { 477 Expected<size_t> ReadBytes = 478 sys::fs::readNativeFileSlice(FD, ToRead, Offset); 479 if (!ReadBytes) 480 return errorToErrorCode(ReadBytes.takeError()); 481 if (*ReadBytes == 0) { 482 std::memset(ToRead.data(), 0, ToRead.size()); 483 break; 484 } 485 ToRead = ToRead.drop_front(*ReadBytes); 486 Offset += *ReadBytes; 487 } 488 489 return std::move(Buf); 490 } 491 492 ErrorOr<std::unique_ptr<MemoryBuffer>> 493 MemoryBuffer::getOpenFile(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize, 494 bool RequiresNullTerminator, bool IsVolatile) { 495 return getOpenFileImpl<MemoryBuffer>(FD, Filename, FileSize, FileSize, 0, 496 RequiresNullTerminator, IsVolatile); 497 } 498 499 ErrorOr<std::unique_ptr<MemoryBuffer>> 500 MemoryBuffer::getOpenFileSlice(sys::fs::file_t FD, const Twine &Filename, uint64_t MapSize, 501 int64_t Offset, bool IsVolatile) { 502 assert(MapSize != uint64_t(-1)); 503 return getOpenFileImpl<MemoryBuffer>(FD, Filename, -1, MapSize, Offset, false, 504 IsVolatile); 505 } 506 507 ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getSTDIN() { 508 // Read in all of the data from stdin, we cannot mmap stdin. 509 // 510 // FIXME: That isn't necessarily true, we should try to mmap stdin and 511 // fallback if it fails. 512 sys::ChangeStdinMode(sys::fs::OF_Text); 513 514 return getMemoryBufferForStream(sys::fs::getStdinHandle(), "<stdin>"); 515 } 516 517 ErrorOr<std::unique_ptr<MemoryBuffer>> 518 MemoryBuffer::getFileAsStream(const Twine &Filename) { 519 Expected<sys::fs::file_t> FDOrErr = 520 sys::fs::openNativeFileForRead(Filename, sys::fs::OF_None); 521 if (!FDOrErr) 522 return errorToErrorCode(FDOrErr.takeError()); 523 sys::fs::file_t FD = *FDOrErr; 524 ErrorOr<std::unique_ptr<MemoryBuffer>> Ret = 525 getMemoryBufferForStream(FD, Filename); 526 sys::fs::closeFile(FD); 527 return Ret; 528 } 529 530 MemoryBufferRef MemoryBuffer::getMemBufferRef() const { 531 StringRef Data = getBuffer(); 532 StringRef Identifier = getBufferIdentifier(); 533 return MemoryBufferRef(Data, Identifier); 534 } 535 536 SmallVectorMemoryBuffer::~SmallVectorMemoryBuffer() {} 537