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"
24 #include "llvm/Support/SmallVectorMemoryBuffer.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) {
62 memcpy(Memory, Data.data(), Data.size());
63 Memory[Data.size()] = 0; // Null terminate string.
67 struct NamedBufferAlloc {
69 NamedBufferAlloc(const Twine &Name) : Name(Name) {}
73 void *operator new(size_t N, const NamedBufferAlloc &Alloc) {
74 SmallString<256> NameBuf;
75 StringRef NameRef = Alloc.Name.toStringRef(NameBuf);
77 char *Mem = static_cast<char *>(operator new(N + NameRef.size() + 1));
78 CopyStringRef(Mem + N, NameRef);
83 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
85 class MemoryBufferMem : public MB {
87 MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
88 MemoryBuffer::init(InputData.begin(), InputData.end(),
89 RequiresNullTerminator);
92 /// Disable sized deallocation for MemoryBufferMem, because it has
93 /// tail-allocated data.
94 void operator delete(void *p) { ::operator delete(p); }
96 StringRef getBufferIdentifier() const override {
97 // The name is stored after the class itself.
98 return StringRef(reinterpret_cast<const char *>(this + 1));
101 MemoryBuffer::BufferKind getBufferKind() const override {
102 return MemoryBuffer::MemoryBuffer_Malloc;
107 template <typename MB>
108 static ErrorOr<std::unique_ptr<MB>>
109 getFileAux(const Twine &Filename, int64_t FileSize, uint64_t MapSize,
110 uint64_t Offset, bool RequiresNullTerminator, bool IsVolatile);
112 std::unique_ptr<MemoryBuffer>
113 MemoryBuffer::getMemBuffer(StringRef InputData, StringRef BufferName,
114 bool RequiresNullTerminator) {
115 auto *Ret = new (NamedBufferAlloc(BufferName))
116 MemoryBufferMem<MemoryBuffer>(InputData, RequiresNullTerminator);
117 return std::unique_ptr<MemoryBuffer>(Ret);
120 std::unique_ptr<MemoryBuffer>
121 MemoryBuffer::getMemBuffer(MemoryBufferRef Ref, bool RequiresNullTerminator) {
122 return std::unique_ptr<MemoryBuffer>(getMemBuffer(
123 Ref.getBuffer(), Ref.getBufferIdentifier(), RequiresNullTerminator));
126 static ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
127 getMemBufferCopyImpl(StringRef InputData, const Twine &BufferName) {
128 auto Buf = WritableMemoryBuffer::getNewUninitMemBuffer(InputData.size(), BufferName);
130 return make_error_code(errc::not_enough_memory);
131 memcpy(Buf->getBufferStart(), InputData.data(), InputData.size());
132 return std::move(Buf);
135 std::unique_ptr<MemoryBuffer>
136 MemoryBuffer::getMemBufferCopy(StringRef InputData, const Twine &BufferName) {
137 auto Buf = getMemBufferCopyImpl(InputData, BufferName);
139 return std::move(*Buf);
143 ErrorOr<std::unique_ptr<MemoryBuffer>>
144 MemoryBuffer::getFileOrSTDIN(const Twine &Filename, int64_t FileSize,
145 bool RequiresNullTerminator) {
146 SmallString<256> NameBuf;
147 StringRef NameRef = Filename.toStringRef(NameBuf);
151 return getFile(Filename, FileSize, RequiresNullTerminator);
154 ErrorOr<std::unique_ptr<MemoryBuffer>>
155 MemoryBuffer::getFileSlice(const Twine &FilePath, uint64_t MapSize,
156 uint64_t Offset, bool IsVolatile) {
157 return getFileAux<MemoryBuffer>(FilePath, -1, MapSize, Offset, false,
161 //===----------------------------------------------------------------------===//
162 // MemoryBuffer::getFile implementation.
163 //===----------------------------------------------------------------------===//
166 /// Memory maps a file descriptor using sys::fs::mapped_file_region.
168 /// This handles converting the offset into a legal offset on the platform.
169 template<typename MB>
170 class MemoryBufferMMapFile : public MB {
171 sys::fs::mapped_file_region MFR;
173 static uint64_t getLegalMapOffset(uint64_t Offset) {
174 return Offset & ~(sys::fs::mapped_file_region::alignment() - 1);
177 static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) {
178 return Len + (Offset - getLegalMapOffset(Offset));
181 const char *getStart(uint64_t Len, uint64_t Offset) {
182 return MFR.const_data() + (Offset - getLegalMapOffset(Offset));
186 MemoryBufferMMapFile(bool RequiresNullTerminator, int FD, uint64_t Len,
187 uint64_t Offset, std::error_code &EC)
188 : MFR(FD, MB::Mapmode, getLegalMapSize(Len, Offset),
189 getLegalMapOffset(Offset), EC) {
191 const char *Start = getStart(Len, Offset);
192 MemoryBuffer::init(Start, Start + Len, RequiresNullTerminator);
196 /// Disable sized deallocation for MemoryBufferMMapFile, because it has
197 /// tail-allocated data.
198 void operator delete(void *p) { ::operator delete(p); }
200 StringRef getBufferIdentifier() const override {
201 // The name is stored after the class itself.
202 return StringRef(reinterpret_cast<const char *>(this + 1));
205 MemoryBuffer::BufferKind getBufferKind() const override {
206 return MemoryBuffer::MemoryBuffer_MMap;
211 static ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
212 getMemoryBufferForStream(int FD, const Twine &BufferName) {
213 const ssize_t ChunkSize = 4096*4;
214 SmallString<ChunkSize> Buffer;
216 // Read into Buffer until we hit EOF.
218 Buffer.reserve(Buffer.size() + ChunkSize);
219 ReadBytes = read(FD, Buffer.end(), ChunkSize);
220 if (ReadBytes == -1) {
221 if (errno == EINTR) continue;
222 return std::error_code(errno, std::generic_category());
224 Buffer.set_size(Buffer.size() + ReadBytes);
225 } while (ReadBytes != 0);
227 return getMemBufferCopyImpl(Buffer, BufferName);
231 ErrorOr<std::unique_ptr<MemoryBuffer>>
232 MemoryBuffer::getFile(const Twine &Filename, int64_t FileSize,
233 bool RequiresNullTerminator, bool IsVolatile) {
234 return getFileAux<MemoryBuffer>(Filename, FileSize, FileSize, 0,
235 RequiresNullTerminator, IsVolatile);
238 template <typename MB>
239 static ErrorOr<std::unique_ptr<MB>>
240 getOpenFileImpl(int FD, const Twine &Filename, uint64_t FileSize,
241 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
244 template <typename MB>
245 static ErrorOr<std::unique_ptr<MB>>
246 getFileAux(const Twine &Filename, int64_t FileSize, uint64_t MapSize,
247 uint64_t Offset, bool RequiresNullTerminator, bool IsVolatile) {
249 std::error_code EC = sys::fs::openFileForRead(Filename, FD, sys::fs::OF_None);
254 auto Ret = getOpenFileImpl<MB>(FD, Filename, FileSize, MapSize, Offset,
255 RequiresNullTerminator, IsVolatile);
260 ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
261 WritableMemoryBuffer::getFile(const Twine &Filename, int64_t FileSize,
263 return getFileAux<WritableMemoryBuffer>(Filename, FileSize, FileSize, 0,
264 /*RequiresNullTerminator*/ false,
268 ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
269 WritableMemoryBuffer::getFileSlice(const Twine &Filename, uint64_t MapSize,
270 uint64_t Offset, bool IsVolatile) {
271 return getFileAux<WritableMemoryBuffer>(Filename, -1, MapSize, Offset, false,
275 std::unique_ptr<WritableMemoryBuffer>
276 WritableMemoryBuffer::getNewUninitMemBuffer(size_t Size, const Twine &BufferName) {
277 using MemBuffer = MemoryBufferMem<WritableMemoryBuffer>;
278 // Allocate space for the MemoryBuffer, the data and the name. It is important
279 // that MemoryBuffer and data are aligned so PointerIntPair works with them.
280 // TODO: Is 16-byte alignment enough? We copy small object files with large
281 // alignment expectations into this buffer.
282 SmallString<256> NameBuf;
283 StringRef NameRef = BufferName.toStringRef(NameBuf);
284 size_t AlignedStringLen = alignTo(sizeof(MemBuffer) + NameRef.size() + 1, 16);
285 size_t RealLen = AlignedStringLen + Size + 1;
286 char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
290 // The name is stored after the class itself.
291 CopyStringRef(Mem + sizeof(MemBuffer), NameRef);
293 // The buffer begins after the name and must be aligned.
294 char *Buf = Mem + AlignedStringLen;
295 Buf[Size] = 0; // Null terminate buffer.
297 auto *Ret = new (Mem) MemBuffer(StringRef(Buf, Size), true);
298 return std::unique_ptr<WritableMemoryBuffer>(Ret);
301 std::unique_ptr<WritableMemoryBuffer>
302 WritableMemoryBuffer::getNewMemBuffer(size_t Size, const Twine &BufferName) {
303 auto SB = WritableMemoryBuffer::getNewUninitMemBuffer(Size, BufferName);
306 memset(SB->getBufferStart(), 0, Size);
310 static bool shouldUseMmap(int FD,
314 bool RequiresNullTerminator,
317 // mmap may leave the buffer without null terminator if the file size changed
318 // by the time the last page is mapped in, so avoid it if the file size is
323 // We don't use mmap for small files because this can severely fragment our
325 if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize)
328 if (!RequiresNullTerminator)
331 // If we don't know the file size, use fstat to find out. fstat on an open
332 // file descriptor is cheaper than stat on a random path.
333 // FIXME: this chunk of code is duplicated, but it avoids a fstat when
334 // RequiresNullTerminator = false and MapSize != -1.
335 if (FileSize == size_t(-1)) {
336 sys::fs::file_status Status;
337 if (sys::fs::status(FD, Status))
339 FileSize = Status.getSize();
342 // If we need a null terminator and the end of the map is inside the file,
343 // we cannot use mmap.
344 size_t End = Offset + MapSize;
345 assert(End <= FileSize);
349 // Don't try to map files that are exactly a multiple of the system page size
350 // if we need a null terminator.
351 if ((FileSize & (PageSize -1)) == 0)
354 #if defined(__CYGWIN__)
355 // Don't try to map files that are exactly a multiple of the physical page size
356 // if we need a null terminator.
357 // FIXME: We should reorganize again getPageSize() on Win32.
358 if ((FileSize & (4096 - 1)) == 0)
365 static ErrorOr<std::unique_ptr<WriteThroughMemoryBuffer>>
366 getReadWriteFile(const Twine &Filename, uint64_t FileSize, uint64_t MapSize,
369 std::error_code EC = sys::fs::openFileForReadWrite(
370 Filename, FD, sys::fs::CD_OpenExisting, sys::fs::OF_None);
375 // Default is to map the full file.
376 if (MapSize == uint64_t(-1)) {
377 // If we don't know the file size, use fstat to find out. fstat on an open
378 // file descriptor is cheaper than stat on a random path.
379 if (FileSize == uint64_t(-1)) {
380 sys::fs::file_status Status;
381 std::error_code EC = sys::fs::status(FD, Status);
385 // If this not a file or a block device (e.g. it's a named pipe
386 // or character device), we can't mmap it, so error out.
387 sys::fs::file_type Type = Status.type();
388 if (Type != sys::fs::file_type::regular_file &&
389 Type != sys::fs::file_type::block_file)
390 return make_error_code(errc::invalid_argument);
392 FileSize = Status.getSize();
397 std::unique_ptr<WriteThroughMemoryBuffer> Result(
398 new (NamedBufferAlloc(Filename))
399 MemoryBufferMMapFile<WriteThroughMemoryBuffer>(false, FD, MapSize,
403 return std::move(Result);
406 ErrorOr<std::unique_ptr<WriteThroughMemoryBuffer>>
407 WriteThroughMemoryBuffer::getFile(const Twine &Filename, int64_t FileSize) {
408 return getReadWriteFile(Filename, FileSize, FileSize, 0);
411 /// Map a subrange of the specified file as a WritableMemoryBuffer.
412 ErrorOr<std::unique_ptr<WriteThroughMemoryBuffer>>
413 WriteThroughMemoryBuffer::getFileSlice(const Twine &Filename, uint64_t MapSize,
415 return getReadWriteFile(Filename, -1, MapSize, Offset);
418 template <typename MB>
419 static ErrorOr<std::unique_ptr<MB>>
420 getOpenFileImpl(int FD, const Twine &Filename, uint64_t FileSize,
421 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
423 static int PageSize = sys::Process::getPageSize();
425 // Default is to map the full file.
426 if (MapSize == uint64_t(-1)) {
427 // If we don't know the file size, use fstat to find out. fstat on an open
428 // file descriptor is cheaper than stat on a random path.
429 if (FileSize == uint64_t(-1)) {
430 sys::fs::file_status Status;
431 std::error_code EC = sys::fs::status(FD, Status);
435 // If this not a file or a block device (e.g. it's a named pipe
436 // or character device), we can't trust the size. Create the memory
437 // buffer by copying off the stream.
438 sys::fs::file_type Type = Status.type();
439 if (Type != sys::fs::file_type::regular_file &&
440 Type != sys::fs::file_type::block_file)
441 return getMemoryBufferForStream(FD, Filename);
443 FileSize = Status.getSize();
448 if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
449 PageSize, IsVolatile)) {
451 std::unique_ptr<MB> Result(
452 new (NamedBufferAlloc(Filename)) MemoryBufferMMapFile<MB>(
453 RequiresNullTerminator, FD, MapSize, Offset, EC));
455 return std::move(Result);
458 auto Buf = WritableMemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
460 // Failed to create a buffer. The only way it can fail is if
461 // new(std::nothrow) returns 0.
462 return make_error_code(errc::not_enough_memory);
465 char *BufPtr = Buf.get()->getBufferStart();
467 size_t BytesLeft = MapSize;
469 if (lseek(FD, Offset, SEEK_SET) == -1)
470 return std::error_code(errno, std::generic_category());
475 ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset);
477 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
482 // Error while reading.
483 return std::error_code(errno, std::generic_category());
486 memset(BufPtr, 0, BytesLeft); // zero-initialize rest of the buffer.
489 BytesLeft -= NumRead;
493 return std::move(Buf);
496 ErrorOr<std::unique_ptr<MemoryBuffer>>
497 MemoryBuffer::getOpenFile(int FD, const Twine &Filename, uint64_t FileSize,
498 bool RequiresNullTerminator, bool IsVolatile) {
499 return getOpenFileImpl<MemoryBuffer>(FD, Filename, FileSize, FileSize, 0,
500 RequiresNullTerminator, IsVolatile);
503 ErrorOr<std::unique_ptr<MemoryBuffer>>
504 MemoryBuffer::getOpenFileSlice(int FD, const Twine &Filename, uint64_t MapSize,
505 int64_t Offset, bool IsVolatile) {
506 assert(MapSize != uint64_t(-1));
507 return getOpenFileImpl<MemoryBuffer>(FD, Filename, -1, MapSize, Offset, false,
511 ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getSTDIN() {
512 // Read in all of the data from stdin, we cannot mmap stdin.
514 // FIXME: That isn't necessarily true, we should try to mmap stdin and
515 // fallback if it fails.
516 sys::ChangeStdinToBinary();
518 return getMemoryBufferForStream(0, "<stdin>");
521 ErrorOr<std::unique_ptr<MemoryBuffer>>
522 MemoryBuffer::getFileAsStream(const Twine &Filename) {
524 std::error_code EC = sys::fs::openFileForRead(Filename, FD, sys::fs::OF_None);
527 ErrorOr<std::unique_ptr<MemoryBuffer>> Ret =
528 getMemoryBufferForStream(FD, Filename);
533 MemoryBufferRef MemoryBuffer::getMemBufferRef() const {
534 StringRef Data = getBuffer();
535 StringRef Identifier = getBufferIdentifier();
536 return MemoryBufferRef(Data, Identifier);
539 void MemoryBuffer::anchor() {}
540 void SmallVectorMemoryBuffer::anchor() {}