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.
83 class MemoryBufferMem : public MemoryBuffer {
85 MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
86 init(InputData.begin(), InputData.end(), RequiresNullTerminator);
89 /// Disable sized deallocation for MemoryBufferMem, because it has
90 /// tail-allocated data.
91 void operator delete(void *p) { ::operator delete(p); }
93 StringRef getBufferIdentifier() const override {
94 // The name is stored after the class itself.
95 return StringRef(reinterpret_cast<const char *>(this + 1));
98 BufferKind getBufferKind() const override {
99 return MemoryBuffer_Malloc;
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);
108 std::unique_ptr<MemoryBuffer>
109 MemoryBuffer::getMemBuffer(StringRef InputData, StringRef BufferName,
110 bool RequiresNullTerminator) {
111 auto *Ret = new (NamedBufferAlloc(BufferName))
112 MemoryBufferMem(InputData, RequiresNullTerminator);
113 return std::unique_ptr<MemoryBuffer>(Ret);
116 std::unique_ptr<MemoryBuffer>
117 MemoryBuffer::getMemBuffer(MemoryBufferRef Ref, bool RequiresNullTerminator) {
118 return std::unique_ptr<MemoryBuffer>(getMemBuffer(
119 Ref.getBuffer(), Ref.getBufferIdentifier(), RequiresNullTerminator));
122 std::unique_ptr<MemoryBuffer>
123 MemoryBuffer::getMemBufferCopy(StringRef InputData, const Twine &BufferName) {
124 std::unique_ptr<MemoryBuffer> Buf =
125 getNewUninitMemBuffer(InputData.size(), BufferName);
128 memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
133 std::unique_ptr<MemoryBuffer>
134 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 SmallString<256> NameBuf;
140 StringRef NameRef = BufferName.toStringRef(NameBuf);
141 size_t AlignedStringLen =
142 alignTo(sizeof(MemoryBufferMem) + NameRef.size() + 1, 16);
143 size_t RealLen = AlignedStringLen + Size + 1;
144 char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
148 // The name is stored after the class itself.
149 CopyStringRef(Mem + sizeof(MemoryBufferMem), NameRef);
151 // The buffer begins after the name and must be aligned.
152 char *Buf = Mem + AlignedStringLen;
153 Buf[Size] = 0; // Null terminate buffer.
155 auto *Ret = new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
156 return std::unique_ptr<MemoryBuffer>(Ret);
159 std::unique_ptr<MemoryBuffer>
160 MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
161 std::unique_ptr<MemoryBuffer> SB = getNewUninitMemBuffer(Size, BufferName);
164 memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
168 ErrorOr<std::unique_ptr<MemoryBuffer>>
169 MemoryBuffer::getFileOrSTDIN(const Twine &Filename, int64_t FileSize,
170 bool RequiresNullTerminator) {
171 SmallString<256> NameBuf;
172 StringRef NameRef = Filename.toStringRef(NameBuf);
176 return getFile(Filename, FileSize, RequiresNullTerminator);
179 ErrorOr<std::unique_ptr<MemoryBuffer>>
180 MemoryBuffer::getFileSlice(const Twine &FilePath, uint64_t MapSize,
181 uint64_t Offset, bool IsVolatile) {
182 return getFileAux(FilePath, -1, MapSize, Offset, false, IsVolatile);
186 //===----------------------------------------------------------------------===//
187 // MemoryBuffer::getFile implementation.
188 //===----------------------------------------------------------------------===//
191 /// \brief Memory maps a file descriptor using sys::fs::mapped_file_region.
193 /// This handles converting the offset into a legal offset on the platform.
194 class MemoryBufferMMapFile : public MemoryBuffer {
195 sys::fs::mapped_file_region MFR;
197 static uint64_t getLegalMapOffset(uint64_t Offset) {
198 return Offset & ~(sys::fs::mapped_file_region::alignment() - 1);
201 static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) {
202 return Len + (Offset - getLegalMapOffset(Offset));
205 const char *getStart(uint64_t Len, uint64_t Offset) {
206 return MFR.const_data() + (Offset - getLegalMapOffset(Offset));
210 MemoryBufferMMapFile(bool RequiresNullTerminator, int FD, uint64_t Len,
211 uint64_t Offset, std::error_code &EC)
212 : MFR(FD, sys::fs::mapped_file_region::readonly,
213 getLegalMapSize(Len, Offset), getLegalMapOffset(Offset), EC) {
215 const char *Start = getStart(Len, Offset);
216 init(Start, Start + Len, RequiresNullTerminator);
220 /// Disable sized deallocation for MemoryBufferMMapFile, because it has
221 /// tail-allocated data.
222 void operator delete(void *p) { ::operator delete(p); }
224 StringRef getBufferIdentifier() const override {
225 // The name is stored after the class itself.
226 return StringRef(reinterpret_cast<const char *>(this + 1));
229 BufferKind getBufferKind() const override {
230 return MemoryBuffer_MMap;
235 static ErrorOr<std::unique_ptr<MemoryBuffer>>
236 getMemoryBufferForStream(int FD, const Twine &BufferName) {
237 const ssize_t ChunkSize = 4096*4;
238 SmallString<ChunkSize> Buffer;
240 // Read into Buffer until we hit EOF.
242 Buffer.reserve(Buffer.size() + ChunkSize);
243 ReadBytes = sys::RetryAfterSignal(-1, read, FD, Buffer.end(), ChunkSize);
245 return std::error_code(errno, std::generic_category());
246 Buffer.set_size(Buffer.size() + ReadBytes);
247 } while (ReadBytes != 0);
249 return MemoryBuffer::getMemBufferCopy(Buffer, BufferName);
253 ErrorOr<std::unique_ptr<MemoryBuffer>>
254 MemoryBuffer::getFile(const Twine &Filename, int64_t FileSize,
255 bool RequiresNullTerminator, bool IsVolatile) {
256 return getFileAux(Filename, FileSize, FileSize, 0,
257 RequiresNullTerminator, IsVolatile);
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,
265 static ErrorOr<std::unique_ptr<MemoryBuffer>>
266 getFileAux(const Twine &Filename, int64_t FileSize, uint64_t MapSize,
267 uint64_t Offset, bool RequiresNullTerminator, bool IsVolatile) {
269 std::error_code EC = sys::fs::openFileForRead(Filename, FD);
273 ErrorOr<std::unique_ptr<MemoryBuffer>> Ret =
274 getOpenFileImpl(FD, Filename, FileSize, MapSize, Offset,
275 RequiresNullTerminator, IsVolatile);
280 static bool shouldUseMmap(int FD,
284 bool RequiresNullTerminator,
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
293 // We don't use mmap for small files because this can severely fragment our
295 if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize)
298 if (!RequiresNullTerminator)
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 if (FileSize == size_t(-1)) {
306 sys::fs::file_status Status;
307 if (sys::fs::status(FD, Status))
309 FileSize = Status.getSize();
312 // If we need a null terminator and the end of the map is inside the file,
313 // we cannot use mmap.
314 size_t End = Offset + MapSize;
315 assert(End <= FileSize);
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 if ((FileSize & (PageSize -1)) == 0)
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)
335 static ErrorOr<std::unique_ptr<MemoryBuffer>>
336 getOpenFileImpl(int FD, const Twine &Filename, uint64_t FileSize,
337 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
339 static int PageSize = sys::Process::getPageSize();
341 // Default is to map the full file.
342 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 if (FileSize == uint64_t(-1)) {
346 sys::fs::file_status Status;
347 std::error_code EC = sys::fs::status(FD, Status);
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 sys::fs::file_type Type = Status.type();
355 if (Type != sys::fs::file_type::regular_file &&
356 Type != sys::fs::file_type::block_file)
357 return getMemoryBufferForStream(FD, Filename);
359 FileSize = Status.getSize();
364 if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
365 PageSize, IsVolatile)) {
367 std::unique_ptr<MemoryBuffer> Result(
368 new (NamedBufferAlloc(Filename))
369 MemoryBufferMMapFile(RequiresNullTerminator, FD, MapSize, Offset, EC));
371 return std::move(Result);
374 std::unique_ptr<MemoryBuffer> Buf =
375 MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
377 // Failed to create a buffer. The only way it can fail is if
378 // new(std::nothrow) returns 0.
379 return make_error_code(errc::not_enough_memory);
382 char *BufPtr = const_cast<char *>(Buf->getBufferStart());
384 size_t BytesLeft = MapSize;
386 if (lseek(FD, Offset, SEEK_SET) == -1)
387 return std::error_code(errno, std::generic_category());
392 ssize_t NumRead = sys::RetryAfterSignal(-1, ::pread, FD, BufPtr, BytesLeft,
393 MapSize - BytesLeft + Offset);
395 ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, BufPtr, BytesLeft);
398 // Error while reading.
399 return std::error_code(errno, std::generic_category());
402 memset(BufPtr, 0, BytesLeft); // zero-initialize rest of the buffer.
405 BytesLeft -= NumRead;
409 return std::move(Buf);
412 ErrorOr<std::unique_ptr<MemoryBuffer>>
413 MemoryBuffer::getOpenFile(int FD, const Twine &Filename, uint64_t FileSize,
414 bool RequiresNullTerminator, bool IsVolatile) {
415 return getOpenFileImpl(FD, Filename, FileSize, FileSize, 0,
416 RequiresNullTerminator, IsVolatile);
419 ErrorOr<std::unique_ptr<MemoryBuffer>>
420 MemoryBuffer::getOpenFileSlice(int FD, const Twine &Filename, uint64_t MapSize,
421 int64_t Offset, bool IsVolatile) {
422 assert(MapSize != uint64_t(-1));
423 return getOpenFileImpl(FD, Filename, -1, MapSize, Offset, false, IsVolatile);
426 ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getSTDIN() {
427 // Read in all of the data from stdin, we cannot mmap stdin.
429 // FIXME: That isn't necessarily true, we should try to mmap stdin and
430 // fallback if it fails.
431 sys::ChangeStdinToBinary();
433 return getMemoryBufferForStream(0, "<stdin>");
436 ErrorOr<std::unique_ptr<MemoryBuffer>>
437 MemoryBuffer::getFileAsStream(const Twine &Filename) {
439 std::error_code EC = sys::fs::openFileForRead(Filename, FD);
442 ErrorOr<std::unique_ptr<MemoryBuffer>> Ret =
443 getMemoryBufferForStream(FD, Filename);
448 MemoryBufferRef MemoryBuffer::getMemBufferRef() const {
449 StringRef Data = getBuffer();
450 StringRef Identifier = getBufferIdentifier();
451 return MemoryBufferRef(Data, Identifier);