LCOV - code coverage report
Current view: top level - lib/Support - MemoryBuffer.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 144 155 92.9 %
Date: 2017-09-14 15:23:50 Functions: 26 30 86.7 %
Legend: Lines: hit not hit

          Line data    Source code
       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 <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      664069 : 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      684263 : 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      684263 :   BufferStart = BufStart;
      50      684263 :   BufferEnd = BufEnd;
      51      684263 : }
      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      683939 :   if (!Data.empty())
      61      666369 :     memcpy(Memory, Data.data(), Data.size());
      62      683939 :   Memory[Data.size()] = 0; // Null terminate string.
      63             : }
      64             : 
      65             : namespace {
      66             : struct NamedBufferAlloc {
      67             :   const Twine &Name;
      68      219235 :   NamedBufferAlloc(const Twine &Name) : Name(Name) {}
      69             : };
      70             : }
      71             : 
      72      219235 : void *operator new(size_t N, const NamedBufferAlloc &Alloc) {
      73      438470 :   SmallString<256> NameBuf;
      74      219235 :   StringRef NameRef = Alloc.Name.toStringRef(NameBuf);
      75             : 
      76      219235 :   char *Mem = static_cast<char *>(operator new(N + NameRef.size() + 1));
      77      438470 :   CopyStringRef(Mem + N, NameRef);
      78      438470 :   return Mem;
      79             : }
      80             : 
      81             : namespace {
      82             : /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
      83     1289687 : class MemoryBufferMem : public MemoryBuffer {
      84             : public:
      85      660828 :   MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
      86      856952 :     init(InputData.begin(), InputData.end(), RequiresNullTerminator);
      87             :   }
      88             : 
      89             :   /// Disable sized deallocation for MemoryBufferMem, because it has
      90             :   /// tail-allocated data.
      91      644843 :   void operator delete(void *p) { ::operator delete(p); }
      92             : 
      93      712866 :   StringRef getBufferIdentifier() const override {
      94             :     // The name is stored after the class itself.
      95     1425732 :     return StringRef(reinterpret_cast<const char *>(this + 1));
      96             :   }
      97             : 
      98           1 :   BufferKind getBufferKind() const override {
      99           1 :     return MemoryBuffer_Malloc;
     100             :   }
     101             : };
     102             : }
     103             : 
     104             : static ErrorOr<std::unique_ptr<MemoryBuffer>>
     105             : getFileAux(const Twine &Filename, int64_t FileSize, uint64_t MapSize, 
     106             :            uint64_t Offset, bool RequiresNullTerminator, bool IsVolatile);
     107             : 
     108             : std::unique_ptr<MemoryBuffer>
     109      196124 : MemoryBuffer::getMemBuffer(StringRef InputData, StringRef BufferName,
     110             :                            bool RequiresNullTerminator) {
     111      588372 :   auto *Ret = new (NamedBufferAlloc(BufferName))
     112      784496 :       MemoryBufferMem(InputData, RequiresNullTerminator);
     113      196124 :   return std::unique_ptr<MemoryBuffer>(Ret);
     114             : }
     115             : 
     116             : std::unique_ptr<MemoryBuffer>
     117       31974 : MemoryBuffer::getMemBuffer(MemoryBufferRef Ref, bool RequiresNullTerminator) {
     118             :   return std::unique_ptr<MemoryBuffer>(getMemBuffer(
     119       31974 :       Ref.getBuffer(), Ref.getBufferIdentifier(), RequiresNullTerminator));
     120             : }
     121             : 
     122             : std::unique_ptr<MemoryBuffer>
     123      341558 : MemoryBuffer::getMemBufferCopy(StringRef InputData, const Twine &BufferName) {
     124             :   std::unique_ptr<MemoryBuffer> Buf =
     125      683116 :       getNewUninitMemBuffer(InputData.size(), BufferName);
     126      341558 :   if (!Buf)
     127             :     return nullptr;
     128      683116 :   memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
     129             :          InputData.size());
     130             :   return Buf;
     131             : }
     132             : 
     133             : std::unique_ptr<MemoryBuffer>
     134      464703 : MemoryBuffer::getNewUninitMemBuffer(size_t Size, const Twine &BufferName) {
     135             :   // Allocate space for the MemoryBuffer, the data and the name. It is important
     136             :   // that MemoryBuffer and data are aligned so PointerIntPair works with them.
     137             :   // TODO: Is 16-byte alignment enough?  We copy small object files with large
     138             :   // alignment expectations into this buffer.
     139      929407 :   SmallString<256> NameBuf;
     140      464703 :   StringRef NameRef = BufferName.toStringRef(NameBuf);
     141             :   size_t AlignedStringLen =
     142      929406 :       alignTo(sizeof(MemoryBufferMem) + NameRef.size() + 1, 16);
     143      464703 :   size_t RealLen = AlignedStringLen + Size + 1;
     144      464703 :   char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
     145      464704 :   if (!Mem)
     146             :     return nullptr;
     147             : 
     148             :   // The name is stored after the class itself.
     149      929408 :   CopyStringRef(Mem + sizeof(MemoryBufferMem), NameRef);
     150             : 
     151             :   // The buffer begins after the name and must be aligned.
     152      464704 :   char *Buf = Mem + AlignedStringLen;
     153      464704 :   Buf[Size] = 0; // Null terminate buffer.
     154             : 
     155      929408 :   auto *Ret = new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
     156             :   return std::unique_ptr<MemoryBuffer>(Ret);
     157             : }
     158             : 
     159             : std::unique_ptr<MemoryBuffer>
     160        2023 : MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
     161        4046 :   std::unique_ptr<MemoryBuffer> SB = getNewUninitMemBuffer(Size, BufferName);
     162        2023 :   if (!SB)
     163             :     return nullptr;
     164        2023 :   memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
     165             :   return SB;
     166             : }
     167             : 
     168             : ErrorOr<std::unique_ptr<MemoryBuffer>>
     169      131288 : MemoryBuffer::getFileOrSTDIN(const Twine &Filename, int64_t FileSize,
     170             :                              bool RequiresNullTerminator) {
     171      262576 :   SmallString<256> NameBuf;
     172      131288 :   StringRef NameRef = Filename.toStringRef(NameBuf);
     173             : 
     174      201248 :   if (NameRef == "-")
     175       69960 :     return getSTDIN();
     176       61328 :   return getFile(Filename, FileSize, RequiresNullTerminator);
     177             : }
     178             : 
     179             : ErrorOr<std::unique_ptr<MemoryBuffer>>
     180       15067 : MemoryBuffer::getFileSlice(const Twine &FilePath, uint64_t MapSize, 
     181             :                            uint64_t Offset, bool IsVolatile) {
     182       15067 :   return getFileAux(FilePath, -1, MapSize, Offset, false, IsVolatile);
     183             : }
     184             : 
     185             : 
     186             : //===----------------------------------------------------------------------===//
     187             : // MemoryBuffer::getFile implementation.
     188             : //===----------------------------------------------------------------------===//
     189             : 
     190             : namespace {
     191             : /// \brief Memory maps a file descriptor using sys::fs::mapped_file_region.
     192             : ///
     193             : /// This handles converting the offset into a legal offset on the platform.
     194       37966 : class MemoryBufferMMapFile : public MemoryBuffer {
     195             :   sys::fs::mapped_file_region MFR;
     196             : 
     197             :   static uint64_t getLegalMapOffset(uint64_t Offset) {
     198       69333 :     return Offset & ~(sys::fs::mapped_file_region::alignment() - 1);
     199             :   }
     200             : 
     201             :   static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) {
     202       23111 :     return Len + (Offset - getLegalMapOffset(Offset));
     203             :   }
     204             : 
     205             :   const char *getStart(uint64_t Len, uint64_t Offset) {
     206       46222 :     return MFR.const_data() + (Offset - getLegalMapOffset(Offset));
     207             :   }
     208             : 
     209             : public:
     210       23111 :   MemoryBufferMMapFile(bool RequiresNullTerminator, int FD, uint64_t Len,
     211             :                        uint64_t Offset, std::error_code &EC)
     212       23111 :       : MFR(FD, sys::fs::mapped_file_region::readonly,
     213       69333 :             getLegalMapSize(Len, Offset), getLegalMapOffset(Offset), EC) {
     214       23111 :     if (!EC) {
     215       46222 :       const char *Start = getStart(Len, Offset);
     216       23111 :       init(Start, Start + Len, RequiresNullTerminator);
     217             :     }
     218       23111 :   }
     219             : 
     220             :   /// Disable sized deallocation for MemoryBufferMMapFile, because it has
     221             :   /// tail-allocated data.
     222       18983 :   void operator delete(void *p) { ::operator delete(p); }
     223             : 
     224       42912 :   StringRef getBufferIdentifier() const override {
     225             :     // The name is stored after the class itself.
     226       85824 :     return StringRef(reinterpret_cast<const char *>(this + 1));
     227             :   }
     228             : 
     229           0 :   BufferKind getBufferKind() const override {
     230           0 :     return MemoryBuffer_MMap;
     231             :   }
     232             : };
     233             : }
     234             : 
     235             : static ErrorOr<std::unique_ptr<MemoryBuffer>>
     236      143370 : getMemoryBufferForStream(int FD, const Twine &BufferName) {
     237      143370 :   const ssize_t ChunkSize = 4096*4;
     238      143370 :   SmallString<ChunkSize> Buffer;
     239             :   ssize_t ReadBytes;
     240             :   // Read into Buffer until we hit EOF.
     241             :   do {
     242    22009466 :     Buffer.reserve(Buffer.size() + ChunkSize);
     243    11004733 :     ReadBytes = sys::RetryAfterSignal(-1, read, FD, Buffer.end(), ChunkSize);
     244    11004733 :     if (ReadBytes == -1)
     245           0 :       return std::error_code(errno, std::generic_category());
     246    22009466 :     Buffer.set_size(Buffer.size() + ReadBytes);
     247    11004733 :   } while (ReadBytes != 0);
     248             : 
     249      430110 :   return MemoryBuffer::getMemBufferCopy(Buffer, BufferName);
     250             : }
     251             : 
     252             : 
     253             : ErrorOr<std::unique_ptr<MemoryBuffer>>
     254       86341 : MemoryBuffer::getFile(const Twine &Filename, int64_t FileSize,
     255             :                       bool RequiresNullTerminator, bool IsVolatile) {
     256             :   return getFileAux(Filename, FileSize, FileSize, 0,
     257       86341 :                     RequiresNullTerminator, IsVolatile);
     258             : }
     259             : 
     260             : static ErrorOr<std::unique_ptr<MemoryBuffer>>
     261             : getOpenFileImpl(int FD, const Twine &Filename, uint64_t FileSize,
     262             :                 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
     263             :                 bool IsVolatile);
     264             : 
     265             : static ErrorOr<std::unique_ptr<MemoryBuffer>>
     266      101408 : getFileAux(const Twine &Filename, int64_t FileSize, uint64_t MapSize,
     267             :            uint64_t Offset, bool RequiresNullTerminator, bool IsVolatile) {
     268             :   int FD;
     269      101408 :   std::error_code EC = sys::fs::openFileForRead(Filename, FD);
     270      101410 :   if (EC)
     271             :     return EC;
     272             : 
     273             :   ErrorOr<std::unique_ptr<MemoryBuffer>> Ret =
     274             :       getOpenFileImpl(FD, Filename, FileSize, MapSize, Offset,
     275       82139 :                       RequiresNullTerminator, IsVolatile);
     276       82139 :   close(FD);
     277       82139 :   return Ret;
     278             : }
     279             : 
     280      143457 : static bool shouldUseMmap(int FD,
     281             :                           size_t FileSize,
     282             :                           size_t MapSize,
     283             :                           off_t Offset,
     284             :                           bool RequiresNullTerminator,
     285             :                           int PageSize,
     286             :                           bool IsVolatile) {
     287             :   // mmap may leave the buffer without null terminator if the file size changed
     288             :   // by the time the last page is mapped in, so avoid it if the file size is
     289             :   // likely to change.
     290      143457 :   if (IsVolatile)
     291             :     return false;
     292             : 
     293             :   // We don't use mmap for small files because this can severely fragment our
     294             :   // address space.
     295      140461 :   if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize)
     296             :     return false;
     297             : 
     298       23116 :   if (!RequiresNullTerminator)
     299             :     return true;
     300             : 
     301             :   // If we don't know the file size, use fstat to find out.  fstat on an open
     302             :   // file descriptor is cheaper than stat on a random path.
     303             :   // FIXME: this chunk of code is duplicated, but it avoids a fstat when
     304             :   // RequiresNullTerminator = false and MapSize != -1.
     305       21862 :   if (FileSize == size_t(-1)) {
     306           0 :     sys::fs::file_status Status;
     307           0 :     if (sys::fs::status(FD, Status))
     308           0 :       return false;
     309           0 :     FileSize = Status.getSize();
     310             :   }
     311             : 
     312             :   // If we need a null terminator and the end of the map is inside the file,
     313             :   // we cannot use mmap.
     314       21862 :   size_t End = Offset + MapSize;
     315             :   assert(End <= FileSize);
     316       21862 :   if (End != FileSize)
     317             :     return false;
     318             : 
     319             :   // Don't try to map files that are exactly a multiple of the system page size
     320             :   // if we need a null terminator.
     321       21862 :   if ((FileSize & (PageSize -1)) == 0)
     322             :     return false;
     323             : 
     324             : #if defined(__CYGWIN__)
     325             :   // Don't try to map files that are exactly a multiple of the physical page size
     326             :   // if we need a null terminator.
     327             :   // FIXME: We should reorganize again getPageSize() on Win32.
     328             :   if ((FileSize & (4096 - 1)) == 0)
     329             :     return false;
     330             : #endif
     331             : 
     332       21857 :   return true;
     333             : }
     334             : 
     335             : static ErrorOr<std::unique_ptr<MemoryBuffer>>
     336      143470 : getOpenFileImpl(int FD, const Twine &Filename, uint64_t FileSize,
     337             :                 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
     338             :                 bool IsVolatile) {
     339      143470 :   static int PageSize = sys::Process::getPageSize();
     340             : 
     341             :   // Default is to map the full file.
     342      143470 :   if (MapSize == uint64_t(-1)) {
     343             :     // If we don't know the file size, use fstat to find out.  fstat on an open
     344             :     // file descriptor is cheaper than stat on a random path.
     345       85744 :     if (FileSize == uint64_t(-1)) {
     346       85744 :       sys::fs::file_status Status;
     347       85744 :       std::error_code EC = sys::fs::status(FD, Status);
     348       85744 :       if (EC)
     349          13 :         return EC;
     350             : 
     351             :       // If this not a file or a block device (e.g. it's a named pipe
     352             :       // or character device), we can't trust the size. Create the memory
     353             :       // buffer by copying off the stream.
     354       85744 :       sys::fs::file_type Type = Status.type();
     355      171488 :       if (Type != sys::fs::file_type::regular_file &&
     356       85744 :           Type != sys::fs::file_type::block_file)
     357          13 :         return getMemoryBufferForStream(FD, Filename);
     358             : 
     359      171462 :       FileSize = Status.getSize();
     360             :     }
     361             :     MapSize = FileSize;
     362             :   }
     363             : 
     364      143457 :   if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
     365             :                     PageSize, IsVolatile)) {
     366       23111 :     std::error_code EC;
     367             :     std::unique_ptr<MemoryBuffer> Result(
     368       46222 :         new (NamedBufferAlloc(Filename))
     369       46222 :         MemoryBufferMMapFile(RequiresNullTerminator, FD, MapSize, Offset, EC));
     370       23111 :     if (!EC)
     371       69333 :       return std::move(Result);
     372             :   }
     373             : 
     374             :   std::unique_ptr<MemoryBuffer> Buf =
     375      120346 :       MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
     376      120346 :   if (!Buf) {
     377             :     // Failed to create a buffer. The only way it can fail is if
     378             :     // new(std::nothrow) returns 0.
     379           0 :     return make_error_code(errc::not_enough_memory);
     380             :   }
     381             : 
     382      120346 :   char *BufPtr = const_cast<char *>(Buf->getBufferStart());
     383             : 
     384      120346 :   size_t BytesLeft = MapSize;
     385             : #ifndef HAVE_PREAD
     386             :   if (lseek(FD, Offset, SEEK_SET) == -1)
     387             :     return std::error_code(errno, std::generic_category());
     388             : #endif
     389             : 
     390      360164 :   while (BytesLeft) {
     391             : #ifdef HAVE_PREAD
     392      239818 :     ssize_t NumRead = sys::RetryAfterSignal(-1, ::pread, FD, BufPtr, BytesLeft,
     393      359727 :                                             MapSize - BytesLeft + Offset);
     394             : #else
     395             :     ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, BufPtr, BytesLeft);
     396             : #endif
     397      119909 :     if (NumRead == -1) {
     398             :       // Error while reading.
     399           0 :       return std::error_code(errno, std::generic_category());
     400             :     }
     401      119909 :     if (NumRead == 0) {
     402           0 :       memset(BufPtr, 0, BytesLeft); // zero-initialize rest of the buffer.
     403           0 :       break;
     404             :     }
     405      119909 :     BytesLeft -= NumRead;
     406      119909 :     BufPtr += NumRead;
     407             :   }
     408             : 
     409      120346 :   return std::move(Buf);
     410             : }
     411             : 
     412             : ErrorOr<std::unique_ptr<MemoryBuffer>>
     413       61329 : MemoryBuffer::getOpenFile(int FD, const Twine &Filename, uint64_t FileSize,
     414             :                           bool RequiresNullTerminator, bool IsVolatile) {
     415             :   return getOpenFileImpl(FD, Filename, FileSize, FileSize, 0,
     416       61329 :                          RequiresNullTerminator, IsVolatile);
     417             : }
     418             : 
     419             : ErrorOr<std::unique_ptr<MemoryBuffer>>
     420           2 : MemoryBuffer::getOpenFileSlice(int FD, const Twine &Filename, uint64_t MapSize,
     421             :                                int64_t Offset, bool IsVolatile) {
     422             :   assert(MapSize != uint64_t(-1));
     423           2 :   return getOpenFileImpl(FD, Filename, -1, MapSize, Offset, false, IsVolatile);
     424             : }
     425             : 
     426       70424 : ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getSTDIN() {
     427             :   // Read in all of the data from stdin, we cannot mmap stdin.
     428             :   //
     429             :   // FIXME: That isn't necessarily true, we should try to mmap stdin and
     430             :   // fallback if it fails.
     431       70424 :   sys::ChangeStdinToBinary();
     432             : 
     433       70424 :   return getMemoryBufferForStream(0, "<stdin>");
     434             : }
     435             : 
     436             : ErrorOr<std::unique_ptr<MemoryBuffer>>
     437       72933 : MemoryBuffer::getFileAsStream(const Twine &Filename) {
     438             :   int FD;
     439       72933 :   std::error_code EC = sys::fs::openFileForRead(Filename, FD);
     440       72933 :   if (EC)
     441             :     return EC;
     442             :   ErrorOr<std::unique_ptr<MemoryBuffer>> Ret =
     443       72933 :       getMemoryBufferForStream(FD, Filename);
     444       72933 :   close(FD);
     445       72933 :   return Ret;
     446             : }
     447             : 
     448       40587 : MemoryBufferRef MemoryBuffer::getMemBufferRef() const {
     449       40587 :   StringRef Data = getBuffer();
     450       40587 :   StringRef Identifier = getBufferIdentifier();
     451       40587 :   return MemoryBufferRef(Data, Identifier);
     452             : }

Generated by: LCOV version 1.13