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"
29 #include <sys/types.h>
30 #include <system_error>
31 #if !defined(_MSC_VER) && !defined(__MINGW32__)
38 //===----------------------------------------------------------------------===//
39 // MemoryBuffer implementation itself.
40 //===----------------------------------------------------------------------===//
42 MemoryBuffer::~MemoryBuffer() { }
44 /// init - Initialize this MemoryBuffer as a reference to externally allocated
45 /// memory, memory that we know is already null terminated.
46 void MemoryBuffer::init(const char *BufStart, const char *BufEnd,
47 bool RequiresNullTerminator) {
48 assert((!RequiresNullTerminator || BufEnd[0] == 0) &&
49 "Buffer is not null terminated!");
50 BufferStart = BufStart;
54 //===----------------------------------------------------------------------===//
55 // MemoryBufferMem implementation.
56 //===----------------------------------------------------------------------===//
58 /// CopyStringRef - Copies contents of a StringRef into a block of memory and
59 /// null-terminates it.
60 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 const char *getBufferIdentifier() const override {
90 // The name is stored after the class itself.
91 return reinterpret_cast<const char*>(this + 1);
94 BufferKind getBufferKind() const override {
95 return MemoryBuffer_Malloc;
100 std::unique_ptr<MemoryBuffer>
101 MemoryBuffer::getMemBuffer(StringRef InputData, StringRef BufferName,
102 bool RequiresNullTerminator) {
103 auto *Ret = new (NamedBufferAlloc(BufferName))
104 MemoryBufferMem(InputData, RequiresNullTerminator);
105 return std::unique_ptr<MemoryBuffer>(Ret);
108 std::unique_ptr<MemoryBuffer>
109 MemoryBuffer::getMemBuffer(MemoryBufferRef Ref, bool RequiresNullTerminator) {
110 return std::unique_ptr<MemoryBuffer>(getMemBuffer(
111 Ref.getBuffer(), Ref.getBufferIdentifier(), RequiresNullTerminator));
114 std::unique_ptr<MemoryBuffer>
115 MemoryBuffer::getMemBufferCopy(StringRef InputData, const Twine &BufferName) {
116 std::unique_ptr<MemoryBuffer> Buf =
117 getNewUninitMemBuffer(InputData.size(), BufferName);
120 memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
125 std::unique_ptr<MemoryBuffer>
126 MemoryBuffer::getNewUninitMemBuffer(size_t Size, const Twine &BufferName) {
127 // Allocate space for the MemoryBuffer, the data and the name. It is important
128 // that MemoryBuffer and data are aligned so PointerIntPair works with them.
129 // TODO: Is 16-byte alignment enough? We copy small object files with large
130 // alignment expectations into this buffer.
131 SmallString<256> NameBuf;
132 StringRef NameRef = BufferName.toStringRef(NameBuf);
133 size_t AlignedStringLen =
134 RoundUpToAlignment(sizeof(MemoryBufferMem) + NameRef.size() + 1, 16);
135 size_t RealLen = AlignedStringLen + Size + 1;
136 char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
140 // The name is stored after the class itself.
141 CopyStringRef(Mem + sizeof(MemoryBufferMem), NameRef);
143 // The buffer begins after the name and must be aligned.
144 char *Buf = Mem + AlignedStringLen;
145 Buf[Size] = 0; // Null terminate buffer.
147 auto *Ret = new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
148 return std::unique_ptr<MemoryBuffer>(Ret);
151 std::unique_ptr<MemoryBuffer>
152 MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
153 std::unique_ptr<MemoryBuffer> SB = getNewUninitMemBuffer(Size, BufferName);
156 memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
160 ErrorOr<std::unique_ptr<MemoryBuffer>>
161 MemoryBuffer::getFileOrSTDIN(const Twine &Filename, int64_t FileSize) {
162 SmallString<256> NameBuf;
163 StringRef NameRef = Filename.toStringRef(NameBuf);
167 return getFile(Filename, FileSize);
171 //===----------------------------------------------------------------------===//
172 // MemoryBuffer::getFile implementation.
173 //===----------------------------------------------------------------------===//
176 /// \brief Memory maps a file descriptor using sys::fs::mapped_file_region.
178 /// This handles converting the offset into a legal offset on the platform.
179 class MemoryBufferMMapFile : public MemoryBuffer {
180 sys::fs::mapped_file_region MFR;
182 static uint64_t getLegalMapOffset(uint64_t Offset) {
183 return Offset & ~(sys::fs::mapped_file_region::alignment() - 1);
186 static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) {
187 return Len + (Offset - getLegalMapOffset(Offset));
190 const char *getStart(uint64_t Len, uint64_t Offset) {
191 return MFR.const_data() + (Offset - getLegalMapOffset(Offset));
195 MemoryBufferMMapFile(bool RequiresNullTerminator, int FD, uint64_t Len,
196 uint64_t Offset, std::error_code EC)
197 : MFR(FD, false, sys::fs::mapped_file_region::readonly,
198 getLegalMapSize(Len, Offset), getLegalMapOffset(Offset), EC) {
200 const char *Start = getStart(Len, Offset);
201 init(Start, Start + Len, RequiresNullTerminator);
205 const char *getBufferIdentifier() const override {
206 // The name is stored after the class itself.
207 return reinterpret_cast<const char *>(this + 1);
210 BufferKind getBufferKind() const override {
211 return MemoryBuffer_MMap;
216 static ErrorOr<std::unique_ptr<MemoryBuffer>>
217 getMemoryBufferForStream(int FD, const Twine &BufferName) {
218 const ssize_t ChunkSize = 4096*4;
219 SmallString<ChunkSize> Buffer;
221 // Read into Buffer until we hit EOF.
223 Buffer.reserve(Buffer.size() + ChunkSize);
224 ReadBytes = read(FD, Buffer.end(), ChunkSize);
225 if (ReadBytes == -1) {
226 if (errno == EINTR) continue;
227 return std::error_code(errno, std::generic_category());
229 Buffer.set_size(Buffer.size() + ReadBytes);
230 } while (ReadBytes != 0);
232 return MemoryBuffer::getMemBufferCopy(Buffer, BufferName);
235 static ErrorOr<std::unique_ptr<MemoryBuffer>>
236 getFileAux(const Twine &Filename, int64_t FileSize, bool RequiresNullTerminator,
237 bool IsVolatileSize);
239 ErrorOr<std::unique_ptr<MemoryBuffer>>
240 MemoryBuffer::getFile(const Twine &Filename, int64_t FileSize,
241 bool RequiresNullTerminator, bool IsVolatileSize) {
242 return getFileAux(Filename, FileSize, RequiresNullTerminator,
246 static ErrorOr<std::unique_ptr<MemoryBuffer>>
247 getOpenFileImpl(int FD, const Twine &Filename, uint64_t FileSize,
248 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
249 bool IsVolatileSize);
251 static ErrorOr<std::unique_ptr<MemoryBuffer>>
252 getFileAux(const Twine &Filename, int64_t FileSize, bool RequiresNullTerminator,
253 bool IsVolatileSize) {
255 std::error_code EC = sys::fs::openFileForRead(Filename, FD);
259 ErrorOr<std::unique_ptr<MemoryBuffer>> Ret =
260 getOpenFileImpl(FD, Filename, FileSize, FileSize, 0,
261 RequiresNullTerminator, IsVolatileSize);
266 static bool shouldUseMmap(int FD,
270 bool RequiresNullTerminator,
272 bool IsVolatileSize) {
273 // mmap may leave the buffer without null terminator if the file size changed
274 // by the time the last page is mapped in, so avoid it if the file size is
279 // We don't use mmap for small files because this can severely fragment our
281 if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize)
284 if (!RequiresNullTerminator)
288 // If we don't know the file size, use fstat to find out. fstat on an open
289 // file descriptor is cheaper than stat on a random path.
290 // FIXME: this chunk of code is duplicated, but it avoids a fstat when
291 // RequiresNullTerminator = false and MapSize != -1.
292 if (FileSize == size_t(-1)) {
293 sys::fs::file_status Status;
294 if (sys::fs::status(FD, Status))
296 FileSize = Status.getSize();
299 // If we need a null terminator and the end of the map is inside the file,
300 // we cannot use mmap.
301 size_t End = Offset + MapSize;
302 assert(End <= FileSize);
306 // Don't try to map files that are exactly a multiple of the system page size
307 // if we need a null terminator.
308 if ((FileSize & (PageSize -1)) == 0)
311 #if defined(__CYGWIN__)
312 // Don't try to map files that are exactly a multiple of the physical page size
313 // if we need a null terminator.
314 // FIXME: We should reorganize again getPageSize() on Win32.
315 if ((FileSize & (4096 - 1)) == 0)
322 static ErrorOr<std::unique_ptr<MemoryBuffer>>
323 getOpenFileImpl(int FD, const Twine &Filename, uint64_t FileSize,
324 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
325 bool IsVolatileSize) {
326 static int PageSize = sys::process::get_self()->page_size();
328 // Default is to map the full file.
329 if (MapSize == uint64_t(-1)) {
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 if (FileSize == uint64_t(-1)) {
333 sys::fs::file_status Status;
334 std::error_code EC = sys::fs::status(FD, Status);
338 // If this not a file or a block device (e.g. it's a named pipe
339 // or character device), we can't trust the size. Create the memory
340 // buffer by copying off the stream.
341 sys::fs::file_type Type = Status.type();
342 if (Type != sys::fs::file_type::regular_file &&
343 Type != sys::fs::file_type::block_file)
344 return getMemoryBufferForStream(FD, Filename);
346 FileSize = Status.getSize();
351 if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
352 PageSize, IsVolatileSize)) {
354 std::unique_ptr<MemoryBuffer> Result(
355 new (NamedBufferAlloc(Filename))
356 MemoryBufferMMapFile(RequiresNullTerminator, FD, MapSize, Offset, EC));
358 return std::move(Result);
361 std::unique_ptr<MemoryBuffer> Buf =
362 MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
364 // Failed to create a buffer. The only way it can fail is if
365 // new(std::nothrow) returns 0.
366 return make_error_code(errc::not_enough_memory);
369 char *BufPtr = const_cast<char *>(Buf->getBufferStart());
371 size_t BytesLeft = MapSize;
373 if (lseek(FD, Offset, SEEK_SET) == -1)
374 return std::error_code(errno, std::generic_category());
379 ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset);
381 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
386 // Error while reading.
387 return std::error_code(errno, std::generic_category());
390 memset(BufPtr, 0, BytesLeft); // zero-initialize rest of the buffer.
393 BytesLeft -= NumRead;
397 return std::move(Buf);
400 ErrorOr<std::unique_ptr<MemoryBuffer>>
401 MemoryBuffer::getOpenFile(int FD, const Twine &Filename, uint64_t FileSize,
402 bool RequiresNullTerminator, bool IsVolatileSize) {
403 return getOpenFileImpl(FD, Filename, FileSize, FileSize, 0,
404 RequiresNullTerminator, IsVolatileSize);
407 ErrorOr<std::unique_ptr<MemoryBuffer>>
408 MemoryBuffer::getOpenFileSlice(int FD, const Twine &Filename, uint64_t MapSize,
410 assert(MapSize != uint64_t(-1));
411 return getOpenFileImpl(FD, Filename, -1, MapSize, Offset, false,
412 /*IsVolatileSize*/ false);
415 ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getSTDIN() {
416 // Read in all of the data from stdin, we cannot mmap stdin.
418 // FIXME: That isn't necessarily true, we should try to mmap stdin and
419 // fallback if it fails.
420 sys::ChangeStdinToBinary();
422 return getMemoryBufferForStream(0, "<stdin>");
425 MemoryBufferRef MemoryBuffer::getMemBufferRef() const {
426 StringRef Data = getBuffer();
427 StringRef Identifier = getBufferIdentifier();
428 return MemoryBufferRef(Data, Identifier);