1 //===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the MemoryBuffer interface.
12 //===----------------------------------------------------------------------===//
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"
28 #include <sys/types.h>
29 #include <system_error>
30 #if !defined(_MSC_VER) && !defined(__MINGW32__)
37 //===----------------------------------------------------------------------===//
38 // MemoryBuffer implementation itself.
39 //===----------------------------------------------------------------------===//
41 MemoryBuffer::~MemoryBuffer() { }
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;
53 //===----------------------------------------------------------------------===//
54 // MemoryBufferMem implementation.
55 //===----------------------------------------------------------------------===//
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) {
61 memcpy(Memory, Data.data(), Data.size());
62 Memory[Data.size()] = 0; // Null terminate string.
66 struct NamedBufferAlloc {
68 NamedBufferAlloc(const Twine &Name) : Name(Name) {}
72 void *operator new(size_t N, const NamedBufferAlloc &Alloc) {
73 SmallString<256> NameBuf;
74 StringRef NameRef = Alloc.Name.toStringRef(NameBuf);
76 char *Mem = static_cast<char *>(operator new(N + NameRef.size() + 1));
77 CopyStringRef(Mem + N, NameRef);
82 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
84 class MemoryBufferMem : public MB {
86 MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
87 MemoryBuffer::init(InputData.begin(), InputData.end(),
88 RequiresNullTerminator);
91 /// Disable sized deallocation for MemoryBufferMem, because it has
92 /// tail-allocated data.
93 void operator delete(void *p) { ::operator delete(p); }
95 StringRef getBufferIdentifier() const override {
96 // The name is stored after the class itself.
97 return StringRef(reinterpret_cast<const char *>(this + 1));
100 MemoryBuffer::BufferKind getBufferKind() const override {
101 return MemoryBuffer::MemoryBuffer_Malloc;
106 template <typename MB>
107 static ErrorOr<std::unique_ptr<MB>>
108 getFileAux(const Twine &Filename, int64_t FileSize, uint64_t MapSize,
109 uint64_t Offset, bool RequiresNullTerminator, bool IsVolatile);
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);
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));
125 static ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
126 getMemBufferCopyImpl(StringRef InputData, const Twine &BufferName) {
127 auto Buf = WritableMemoryBuffer::getNewUninitMemBuffer(InputData.size(), BufferName);
129 return make_error_code(errc::not_enough_memory);
130 memcpy(Buf->getBufferStart(), InputData.data(), InputData.size());
131 return std::move(Buf);
134 std::unique_ptr<MemoryBuffer>
135 MemoryBuffer::getMemBufferCopy(StringRef InputData, const Twine &BufferName) {
136 auto Buf = getMemBufferCopyImpl(InputData, BufferName);
138 return std::move(*Buf);
142 std::unique_ptr<MemoryBuffer>
143 MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
144 auto SB = WritableMemoryBuffer::getNewUninitMemBuffer(Size, BufferName);
147 memset(SB->getBufferStart(), 0, Size);
148 return std::move(SB);
151 ErrorOr<std::unique_ptr<MemoryBuffer>>
152 MemoryBuffer::getFileOrSTDIN(const Twine &Filename, int64_t FileSize,
153 bool RequiresNullTerminator) {
154 SmallString<256> NameBuf;
155 StringRef NameRef = Filename.toStringRef(NameBuf);
159 return getFile(Filename, FileSize, RequiresNullTerminator);
162 ErrorOr<std::unique_ptr<MemoryBuffer>>
163 MemoryBuffer::getFileSlice(const Twine &FilePath, uint64_t MapSize,
164 uint64_t Offset, bool IsVolatile) {
165 return getFileAux<MemoryBuffer>(FilePath, -1, MapSize, Offset, false,
169 //===----------------------------------------------------------------------===//
170 // MemoryBuffer::getFile implementation.
171 //===----------------------------------------------------------------------===//
174 /// \brief Memory maps a file descriptor using sys::fs::mapped_file_region.
176 /// This handles converting the offset into a legal offset on the platform.
177 template<typename MB>
178 class MemoryBufferMMapFile : public MB {
179 sys::fs::mapped_file_region MFR;
181 static uint64_t getLegalMapOffset(uint64_t Offset) {
182 return Offset & ~(sys::fs::mapped_file_region::alignment() - 1);
185 static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) {
186 return Len + (Offset - getLegalMapOffset(Offset));
189 const char *getStart(uint64_t Len, uint64_t Offset) {
190 return MFR.const_data() + (Offset - getLegalMapOffset(Offset));
194 MemoryBufferMMapFile(bool RequiresNullTerminator, int FD, uint64_t Len,
195 uint64_t Offset, std::error_code &EC)
197 MB::Writable ? sys::fs::mapped_file_region::priv
198 : sys::fs::mapped_file_region::readonly,
199 getLegalMapSize(Len, Offset), getLegalMapOffset(Offset), EC) {
201 const char *Start = getStart(Len, Offset);
202 MemoryBuffer::init(Start, Start + Len, RequiresNullTerminator);
206 /// Disable sized deallocation for MemoryBufferMMapFile, because it has
207 /// tail-allocated data.
208 void operator delete(void *p) { ::operator delete(p); }
210 StringRef getBufferIdentifier() const override {
211 // The name is stored after the class itself.
212 return StringRef(reinterpret_cast<const char *>(this + 1));
215 MemoryBuffer::BufferKind getBufferKind() const override {
216 return MemoryBuffer::MemoryBuffer_MMap;
221 static ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
222 getMemoryBufferForStream(int FD, const Twine &BufferName) {
223 const ssize_t ChunkSize = 4096*4;
224 SmallString<ChunkSize> Buffer;
226 // Read into Buffer until we hit EOF.
228 Buffer.reserve(Buffer.size() + ChunkSize);
229 ReadBytes = sys::RetryAfterSignal(-1, read, FD, Buffer.end(), ChunkSize);
231 return std::error_code(errno, std::generic_category());
232 Buffer.set_size(Buffer.size() + ReadBytes);
233 } while (ReadBytes != 0);
235 return getMemBufferCopyImpl(Buffer, BufferName);
239 ErrorOr<std::unique_ptr<MemoryBuffer>>
240 MemoryBuffer::getFile(const Twine &Filename, int64_t FileSize,
241 bool RequiresNullTerminator, bool IsVolatile) {
242 return getFileAux<MemoryBuffer>(Filename, FileSize, FileSize, 0,
243 RequiresNullTerminator, IsVolatile);
246 template <typename MB>
247 static ErrorOr<std::unique_ptr<MB>>
248 getOpenFileImpl(int FD, const Twine &Filename, uint64_t FileSize,
249 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
252 template <typename MB>
253 static ErrorOr<std::unique_ptr<MB>>
254 getFileAux(const Twine &Filename, int64_t FileSize, uint64_t MapSize,
255 uint64_t Offset, bool RequiresNullTerminator, bool IsVolatile) {
257 std::error_code EC = sys::fs::openFileForRead(Filename, FD);
262 auto Ret = getOpenFileImpl<MB>(FD, Filename, FileSize, MapSize, Offset,
263 RequiresNullTerminator, IsVolatile);
268 ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
269 WritableMemoryBuffer::getFile(const Twine &Filename, int64_t FileSize,
271 return getFileAux<WritableMemoryBuffer>(Filename, FileSize, FileSize, 0,
272 /*RequiresNullTerminator*/ false,
276 ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
277 WritableMemoryBuffer::getFileSlice(const Twine &Filename, uint64_t MapSize,
278 uint64_t Offset, bool IsVolatile) {
279 return getFileAux<WritableMemoryBuffer>(Filename, -1, MapSize, Offset, false,
283 std::unique_ptr<WritableMemoryBuffer>
284 WritableMemoryBuffer::getNewUninitMemBuffer(size_t Size, const Twine &BufferName) {
285 using MemBuffer = MemoryBufferMem<WritableMemoryBuffer>;
286 // Allocate space for the MemoryBuffer, the data and the name. It is important
287 // that MemoryBuffer and data are aligned so PointerIntPair works with them.
288 // TODO: Is 16-byte alignment enough? We copy small object files with large
289 // alignment expectations into this buffer.
290 SmallString<256> NameBuf;
291 StringRef NameRef = BufferName.toStringRef(NameBuf);
292 size_t AlignedStringLen = alignTo(sizeof(MemBuffer) + NameRef.size() + 1, 16);
293 size_t RealLen = AlignedStringLen + Size + 1;
294 char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
298 // The name is stored after the class itself.
299 CopyStringRef(Mem + sizeof(MemBuffer), NameRef);
301 // The buffer begins after the name and must be aligned.
302 char *Buf = Mem + AlignedStringLen;
303 Buf[Size] = 0; // Null terminate buffer.
305 auto *Ret = new (Mem) MemBuffer(StringRef(Buf, Size), true);
306 return std::unique_ptr<WritableMemoryBuffer>(Ret);
309 static bool shouldUseMmap(int FD,
313 bool RequiresNullTerminator,
316 // mmap may leave the buffer without null terminator if the file size changed
317 // by the time the last page is mapped in, so avoid it if the file size is
322 // We don't use mmap for small files because this can severely fragment our
324 if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize)
327 if (!RequiresNullTerminator)
330 // If we don't know the file size, use fstat to find out. fstat on an open
331 // file descriptor is cheaper than stat on a random path.
332 // FIXME: this chunk of code is duplicated, but it avoids a fstat when
333 // RequiresNullTerminator = false and MapSize != -1.
334 if (FileSize == size_t(-1)) {
335 sys::fs::file_status Status;
336 if (sys::fs::status(FD, Status))
338 FileSize = Status.getSize();
341 // If we need a null terminator and the end of the map is inside the file,
342 // we cannot use mmap.
343 size_t End = Offset + MapSize;
344 assert(End <= FileSize);
348 // Don't try to map files that are exactly a multiple of the system page size
349 // if we need a null terminator.
350 if ((FileSize & (PageSize -1)) == 0)
353 #if defined(__CYGWIN__)
354 // Don't try to map files that are exactly a multiple of the physical page size
355 // if we need a null terminator.
356 // FIXME: We should reorganize again getPageSize() on Win32.
357 if ((FileSize & (4096 - 1)) == 0)
364 template <typename MB>
365 static ErrorOr<std::unique_ptr<MB>>
366 getOpenFileImpl(int FD, const Twine &Filename, uint64_t FileSize,
367 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
369 static int PageSize = sys::Process::getPageSize();
371 // Default is to map the full file.
372 if (MapSize == uint64_t(-1)) {
373 // If we don't know the file size, use fstat to find out. fstat on an open
374 // file descriptor is cheaper than stat on a random path.
375 if (FileSize == uint64_t(-1)) {
376 sys::fs::file_status Status;
377 std::error_code EC = sys::fs::status(FD, Status);
381 // If this not a file or a block device (e.g. it's a named pipe
382 // or character device), we can't trust the size. Create the memory
383 // buffer by copying off the stream.
384 sys::fs::file_type Type = Status.type();
385 if (Type != sys::fs::file_type::regular_file &&
386 Type != sys::fs::file_type::block_file)
387 return getMemoryBufferForStream(FD, Filename);
389 FileSize = Status.getSize();
394 if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
395 PageSize, IsVolatile)) {
397 std::unique_ptr<MB> Result(
398 new (NamedBufferAlloc(Filename)) MemoryBufferMMapFile<MB>(
399 RequiresNullTerminator, FD, MapSize, Offset, EC));
401 return std::move(Result);
404 auto Buf = WritableMemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
406 // Failed to create a buffer. The only way it can fail is if
407 // new(std::nothrow) returns 0.
408 return make_error_code(errc::not_enough_memory);
411 char *BufPtr = Buf.get()->getBufferStart();
413 size_t BytesLeft = MapSize;
415 if (lseek(FD, Offset, SEEK_SET) == -1)
416 return std::error_code(errno, std::generic_category());
421 ssize_t NumRead = sys::RetryAfterSignal(-1, ::pread, FD, BufPtr, BytesLeft,
422 MapSize - BytesLeft + Offset);
424 ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, BufPtr, BytesLeft);
427 // Error while reading.
428 return std::error_code(errno, std::generic_category());
431 memset(BufPtr, 0, BytesLeft); // zero-initialize rest of the buffer.
434 BytesLeft -= NumRead;
438 return std::move(Buf);
441 ErrorOr<std::unique_ptr<MemoryBuffer>>
442 MemoryBuffer::getOpenFile(int FD, const Twine &Filename, uint64_t FileSize,
443 bool RequiresNullTerminator, bool IsVolatile) {
444 return getOpenFileImpl<MemoryBuffer>(FD, Filename, FileSize, FileSize, 0,
445 RequiresNullTerminator, IsVolatile);
448 ErrorOr<std::unique_ptr<MemoryBuffer>>
449 MemoryBuffer::getOpenFileSlice(int FD, const Twine &Filename, uint64_t MapSize,
450 int64_t Offset, bool IsVolatile) {
451 assert(MapSize != uint64_t(-1));
452 return getOpenFileImpl<MemoryBuffer>(FD, Filename, -1, MapSize, Offset, false,
456 ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getSTDIN() {
457 // Read in all of the data from stdin, we cannot mmap stdin.
459 // FIXME: That isn't necessarily true, we should try to mmap stdin and
460 // fallback if it fails.
461 sys::ChangeStdinToBinary();
463 return getMemoryBufferForStream(0, "<stdin>");
466 ErrorOr<std::unique_ptr<MemoryBuffer>>
467 MemoryBuffer::getFileAsStream(const Twine &Filename) {
469 std::error_code EC = sys::fs::openFileForRead(Filename, FD);
472 ErrorOr<std::unique_ptr<MemoryBuffer>> Ret =
473 getMemoryBufferForStream(FD, Filename);
478 MemoryBufferRef MemoryBuffer::getMemBufferRef() const {
479 StringRef Data = getBuffer();
480 StringRef Identifier = getBufferIdentifier();
481 return MemoryBufferRef(Data, Identifier);