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