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