Home | History | Annotate | Download | only in Support
      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 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 }
     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 class MemoryBufferMem : public MemoryBuffer {
     84 public:
     85   MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
     86     init(InputData.begin(), InputData.end(), RequiresNullTerminator);
     87   }
     88 
     89   const char *getBufferIdentifier() const override {
     90      // The name is stored after the class itself.
     91     return reinterpret_cast<const char*>(this + 1);
     92   }
     93 
     94   BufferKind getBufferKind() const override {
     95     return MemoryBuffer_Malloc;
     96   }
     97 };
     98 }
     99 
    100 static ErrorOr<std::unique_ptr<MemoryBuffer>>
    101 getFileAux(const Twine &Filename, int64_t FileSize, uint64_t MapSize,
    102            uint64_t Offset, bool RequiresNullTerminator, bool IsVolatileSize);
    103 
    104 std::unique_ptr<MemoryBuffer>
    105 MemoryBuffer::getMemBuffer(StringRef InputData, StringRef BufferName,
    106                            bool RequiresNullTerminator) {
    107   auto *Ret = new (NamedBufferAlloc(BufferName))
    108       MemoryBufferMem(InputData, RequiresNullTerminator);
    109   return std::unique_ptr<MemoryBuffer>(Ret);
    110 }
    111 
    112 std::unique_ptr<MemoryBuffer>
    113 MemoryBuffer::getMemBuffer(MemoryBufferRef Ref, bool RequiresNullTerminator) {
    114   return std::unique_ptr<MemoryBuffer>(getMemBuffer(
    115       Ref.getBuffer(), Ref.getBufferIdentifier(), RequiresNullTerminator));
    116 }
    117 
    118 std::unique_ptr<MemoryBuffer>
    119 MemoryBuffer::getMemBufferCopy(StringRef InputData, const Twine &BufferName) {
    120   std::unique_ptr<MemoryBuffer> Buf =
    121       getNewUninitMemBuffer(InputData.size(), BufferName);
    122   if (!Buf)
    123     return nullptr;
    124   memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
    125          InputData.size());
    126   return Buf;
    127 }
    128 
    129 std::unique_ptr<MemoryBuffer>
    130 MemoryBuffer::getNewUninitMemBuffer(size_t Size, const Twine &BufferName) {
    131   // Allocate space for the MemoryBuffer, the data and the name. It is important
    132   // that MemoryBuffer and data are aligned so PointerIntPair works with them.
    133   // TODO: Is 16-byte alignment enough?  We copy small object files with large
    134   // alignment expectations into this buffer.
    135   SmallString<256> NameBuf;
    136   StringRef NameRef = BufferName.toStringRef(NameBuf);
    137   size_t AlignedStringLen =
    138       RoundUpToAlignment(sizeof(MemoryBufferMem) + NameRef.size() + 1, 16);
    139   size_t RealLen = AlignedStringLen + Size + 1;
    140   char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
    141   if (!Mem)
    142     return nullptr;
    143 
    144   // The name is stored after the class itself.
    145   CopyStringRef(Mem + sizeof(MemoryBufferMem), NameRef);
    146 
    147   // The buffer begins after the name and must be aligned.
    148   char *Buf = Mem + AlignedStringLen;
    149   Buf[Size] = 0; // Null terminate buffer.
    150 
    151   auto *Ret = new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
    152   return std::unique_ptr<MemoryBuffer>(Ret);
    153 }
    154 
    155 std::unique_ptr<MemoryBuffer>
    156 MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
    157   std::unique_ptr<MemoryBuffer> SB = getNewUninitMemBuffer(Size, BufferName);
    158   if (!SB)
    159     return nullptr;
    160   memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
    161   return SB;
    162 }
    163 
    164 ErrorOr<std::unique_ptr<MemoryBuffer>>
    165 MemoryBuffer::getFileOrSTDIN(const Twine &Filename, int64_t FileSize,
    166                              bool RequiresNullTerminator) {
    167   SmallString<256> NameBuf;
    168   StringRef NameRef = Filename.toStringRef(NameBuf);
    169 
    170   if (NameRef == "-")
    171     return getSTDIN();
    172   return getFile(Filename, FileSize, RequiresNullTerminator);
    173 }
    174 
    175 ErrorOr<std::unique_ptr<MemoryBuffer>>
    176 MemoryBuffer::getFileSlice(const Twine &FilePath, uint64_t MapSize,
    177                            uint64_t Offset) {
    178   return getFileAux(FilePath, -1, MapSize, Offset, false, false);
    179 }
    180 
    181 
    182 //===----------------------------------------------------------------------===//
    183 // MemoryBuffer::getFile implementation.
    184 //===----------------------------------------------------------------------===//
    185 
    186 namespace {
    187 /// \brief Memory maps a file descriptor using sys::fs::mapped_file_region.
    188 ///
    189 /// This handles converting the offset into a legal offset on the platform.
    190 class MemoryBufferMMapFile : public MemoryBuffer {
    191   sys::fs::mapped_file_region MFR;
    192 
    193   static uint64_t getLegalMapOffset(uint64_t Offset) {
    194     return Offset & ~(sys::fs::mapped_file_region::alignment() - 1);
    195   }
    196 
    197   static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) {
    198     return Len + (Offset - getLegalMapOffset(Offset));
    199   }
    200 
    201   const char *getStart(uint64_t Len, uint64_t Offset) {
    202     return MFR.const_data() + (Offset - getLegalMapOffset(Offset));
    203   }
    204 
    205 public:
    206   MemoryBufferMMapFile(bool RequiresNullTerminator, int FD, uint64_t Len,
    207                        uint64_t Offset, std::error_code &EC)
    208       : MFR(FD, sys::fs::mapped_file_region::readonly,
    209             getLegalMapSize(Len, Offset), getLegalMapOffset(Offset), EC) {
    210     if (!EC) {
    211       const char *Start = getStart(Len, Offset);
    212       init(Start, Start + Len, RequiresNullTerminator);
    213     }
    214   }
    215 
    216   const char *getBufferIdentifier() const override {
    217     // The name is stored after the class itself.
    218     return reinterpret_cast<const char *>(this + 1);
    219   }
    220 
    221   BufferKind getBufferKind() const override {
    222     return MemoryBuffer_MMap;
    223   }
    224 };
    225 }
    226 
    227 static ErrorOr<std::unique_ptr<MemoryBuffer>>
    228 getMemoryBufferForStream(int FD, const Twine &BufferName) {
    229   const ssize_t ChunkSize = 4096*4;
    230   SmallString<ChunkSize> Buffer;
    231   ssize_t ReadBytes;
    232   // Read into Buffer until we hit EOF.
    233   do {
    234     Buffer.reserve(Buffer.size() + ChunkSize);
    235     ReadBytes = read(FD, Buffer.end(), ChunkSize);
    236     if (ReadBytes == -1) {
    237       if (errno == EINTR) continue;
    238       return std::error_code(errno, std::generic_category());
    239     }
    240     Buffer.set_size(Buffer.size() + ReadBytes);
    241   } while (ReadBytes != 0);
    242 
    243   return MemoryBuffer::getMemBufferCopy(Buffer, BufferName);
    244 }
    245 
    246 
    247 ErrorOr<std::unique_ptr<MemoryBuffer>>
    248 MemoryBuffer::getFile(const Twine &Filename, int64_t FileSize,
    249                       bool RequiresNullTerminator, bool IsVolatileSize) {
    250   return getFileAux(Filename, FileSize, FileSize, 0,
    251                     RequiresNullTerminator, IsVolatileSize);
    252 }
    253 
    254 static ErrorOr<std::unique_ptr<MemoryBuffer>>
    255 getOpenFileImpl(int FD, const Twine &Filename, uint64_t FileSize,
    256                 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
    257                 bool IsVolatileSize);
    258 
    259 static ErrorOr<std::unique_ptr<MemoryBuffer>>
    260 getFileAux(const Twine &Filename, int64_t FileSize, uint64_t MapSize,
    261            uint64_t Offset, bool RequiresNullTerminator, bool IsVolatileSize) {
    262   int FD;
    263   std::error_code EC = sys::fs::openFileForRead(Filename, FD);
    264   if (EC)
    265     return EC;
    266 
    267   ErrorOr<std::unique_ptr<MemoryBuffer>> Ret =
    268       getOpenFileImpl(FD, Filename, FileSize, MapSize, Offset,
    269                       RequiresNullTerminator, IsVolatileSize);
    270   close(FD);
    271   return Ret;
    272 }
    273 
    274 static bool shouldUseMmap(int FD,
    275                           size_t FileSize,
    276                           size_t MapSize,
    277                           off_t Offset,
    278                           bool RequiresNullTerminator,
    279                           int PageSize,
    280                           bool IsVolatileSize) {
    281   // mmap may leave the buffer without null terminator if the file size changed
    282   // by the time the last page is mapped in, so avoid it if the file size is
    283   // likely to change.
    284   if (IsVolatileSize)
    285     return false;
    286 
    287   // We don't use mmap for small files because this can severely fragment our
    288   // address space.
    289   if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize)
    290     return false;
    291 
    292   if (!RequiresNullTerminator)
    293     return true;
    294 
    295 
    296   // If we don't know the file size, use fstat to find out.  fstat on an open
    297   // file descriptor is cheaper than stat on a random path.
    298   // FIXME: this chunk of code is duplicated, but it avoids a fstat when
    299   // RequiresNullTerminator = false and MapSize != -1.
    300   if (FileSize == size_t(-1)) {
    301     sys::fs::file_status Status;
    302     if (sys::fs::status(FD, Status))
    303       return false;
    304     FileSize = Status.getSize();
    305   }
    306 
    307   // If we need a null terminator and the end of the map is inside the file,
    308   // we cannot use mmap.
    309   size_t End = Offset + MapSize;
    310   assert(End <= FileSize);
    311   if (End != FileSize)
    312     return false;
    313 
    314   // Don't try to map files that are exactly a multiple of the system page size
    315   // if we need a null terminator.
    316   if ((FileSize & (PageSize -1)) == 0)
    317     return false;
    318 
    319 #if defined(__CYGWIN__)
    320   // Don't try to map files that are exactly a multiple of the physical page size
    321   // if we need a null terminator.
    322   // FIXME: We should reorganize again getPageSize() on Win32.
    323   if ((FileSize & (4096 - 1)) == 0)
    324     return false;
    325 #endif
    326 
    327   return true;
    328 }
    329 
    330 static ErrorOr<std::unique_ptr<MemoryBuffer>>
    331 getOpenFileImpl(int FD, const Twine &Filename, uint64_t FileSize,
    332                 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
    333                 bool IsVolatileSize) {
    334   static int PageSize = sys::Process::getPageSize();
    335 
    336   // Default is to map the full file.
    337   if (MapSize == uint64_t(-1)) {
    338     // If we don't know the file size, use fstat to find out.  fstat on an open
    339     // file descriptor is cheaper than stat on a random path.
    340     if (FileSize == uint64_t(-1)) {
    341       sys::fs::file_status Status;
    342       std::error_code EC = sys::fs::status(FD, Status);
    343       if (EC)
    344         return EC;
    345 
    346       // If this not a file or a block device (e.g. it's a named pipe
    347       // or character device), we can't trust the size. Create the memory
    348       // buffer by copying off the stream.
    349       sys::fs::file_type Type = Status.type();
    350       if (Type != sys::fs::file_type::regular_file &&
    351           Type != sys::fs::file_type::block_file)
    352         return getMemoryBufferForStream(FD, Filename);
    353 
    354       FileSize = Status.getSize();
    355     }
    356     MapSize = FileSize;
    357   }
    358 
    359   if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
    360                     PageSize, IsVolatileSize)) {
    361     std::error_code EC;
    362     std::unique_ptr<MemoryBuffer> Result(
    363         new (NamedBufferAlloc(Filename))
    364         MemoryBufferMMapFile(RequiresNullTerminator, FD, MapSize, Offset, EC));
    365     if (!EC)
    366       return std::move(Result);
    367   }
    368 
    369   std::unique_ptr<MemoryBuffer> Buf =
    370       MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
    371   if (!Buf) {
    372     // Failed to create a buffer. The only way it can fail is if
    373     // new(std::nothrow) returns 0.
    374     return make_error_code(errc::not_enough_memory);
    375   }
    376 
    377   char *BufPtr = const_cast<char *>(Buf->getBufferStart());
    378 
    379   size_t BytesLeft = MapSize;
    380 #ifndef HAVE_PREAD
    381   if (lseek(FD, Offset, SEEK_SET) == -1)
    382     return std::error_code(errno, std::generic_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 std::error_code(errno, std::generic_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   return std::move(Buf);
    406 }
    407 
    408 ErrorOr<std::unique_ptr<MemoryBuffer>>
    409 MemoryBuffer::getOpenFile(int FD, const Twine &Filename, uint64_t FileSize,
    410                           bool RequiresNullTerminator, bool IsVolatileSize) {
    411   return getOpenFileImpl(FD, Filename, FileSize, FileSize, 0,
    412                          RequiresNullTerminator, IsVolatileSize);
    413 }
    414 
    415 ErrorOr<std::unique_ptr<MemoryBuffer>>
    416 MemoryBuffer::getOpenFileSlice(int FD, const Twine &Filename, uint64_t MapSize,
    417                                int64_t Offset) {
    418   assert(MapSize != uint64_t(-1));
    419   return getOpenFileImpl(FD, Filename, -1, MapSize, Offset, false,
    420                          /*IsVolatileSize*/ false);
    421 }
    422 
    423 ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getSTDIN() {
    424   // Read in all of the data from stdin, we cannot mmap stdin.
    425   //
    426   // FIXME: That isn't necessarily true, we should try to mmap stdin and
    427   // fallback if it fails.
    428   sys::ChangeStdinToBinary();
    429 
    430   return getMemoryBufferForStream(0, "<stdin>");
    431 }
    432 
    433 MemoryBufferRef MemoryBuffer::getMemBufferRef() const {
    434   StringRef Data = getBuffer();
    435   StringRef Identifier = getBufferIdentifier();
    436   return MemoryBufferRef(Data, Identifier);
    437 }
    438