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/OwningPtr.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/Config/config.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/system_error.h"
30 #include <sys/types.h>
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(StringRef Name) : Name(Name) {}
72 void *operator new(size_t N, const NamedBufferAlloc &Alloc) {
73 char *Mem = static_cast<char *>(operator new(N + Alloc.Name.size() + 1));
74 CopyStringRef(Mem + N, Alloc.Name);
79 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
80 class MemoryBufferMem : public MemoryBuffer {
82 MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
83 init(InputData.begin(), InputData.end(), RequiresNullTerminator);
86 const char *getBufferIdentifier() const override {
87 // The name is stored after the class itself.
88 return reinterpret_cast<const char*>(this + 1);
91 BufferKind getBufferKind() const override {
92 return MemoryBuffer_Malloc;
97 /// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note
98 /// that InputData must be a null terminated if RequiresNullTerminator is true!
99 MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
100 StringRef BufferName,
101 bool RequiresNullTerminator) {
102 return new (NamedBufferAlloc(BufferName))
103 MemoryBufferMem(InputData, RequiresNullTerminator);
106 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
107 /// copying the contents and taking ownership of it. This has no requirements
109 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
110 StringRef BufferName) {
111 MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
112 if (!Buf) return nullptr;
113 memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
118 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
119 /// that is not initialized. Note that the caller should initialize the
120 /// memory allocated by this method. The memory is owned by the MemoryBuffer
122 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
123 StringRef BufferName) {
124 // Allocate space for the MemoryBuffer, the data and the name. It is important
125 // that MemoryBuffer and data are aligned so PointerIntPair works with them.
126 // TODO: Is 16-byte alignment enough? We copy small object files with large
127 // alignment expectations into this buffer.
128 size_t AlignedStringLen =
129 RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1, 16);
130 size_t RealLen = AlignedStringLen + Size + 1;
131 char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
132 if (!Mem) return nullptr;
134 // The name is stored after the class itself.
135 CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
137 // The buffer begins after the name and must be aligned.
138 char *Buf = Mem + AlignedStringLen;
139 Buf[Size] = 0; // Null terminate buffer.
141 return new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
144 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
145 /// is completely initialized to zeros. Note that the caller should
146 /// initialize the memory allocated by this method. The memory is owned by
147 /// the MemoryBuffer object.
148 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
149 MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
150 if (!SB) return nullptr;
151 memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
156 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
157 /// if the Filename is "-". If an error occurs, this returns null and fills
158 /// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
159 /// returns an empty buffer.
160 error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
161 std::unique_ptr<MemoryBuffer> &Result,
164 return getSTDIN(Result);
165 return getFile(Filename, Result, FileSize);
168 error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
169 OwningPtr<MemoryBuffer> &Result,
171 std::unique_ptr<MemoryBuffer> MB;
172 error_code ec = getFileOrSTDIN(Filename, MB, FileSize);
173 Result = std::move(MB);
178 //===----------------------------------------------------------------------===//
179 // MemoryBuffer::getFile implementation.
180 //===----------------------------------------------------------------------===//
183 /// \brief Memory maps a file descriptor using sys::fs::mapped_file_region.
185 /// This handles converting the offset into a legal offset on the platform.
186 class MemoryBufferMMapFile : public MemoryBuffer {
187 sys::fs::mapped_file_region MFR;
189 static uint64_t getLegalMapOffset(uint64_t Offset) {
190 return Offset & ~(sys::fs::mapped_file_region::alignment() - 1);
193 static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) {
194 return Len + (Offset - getLegalMapOffset(Offset));
197 const char *getStart(uint64_t Len, uint64_t Offset) {
198 return MFR.const_data() + (Offset - getLegalMapOffset(Offset));
202 MemoryBufferMMapFile(bool RequiresNullTerminator, int FD, uint64_t Len,
203 uint64_t Offset, error_code EC)
204 : MFR(FD, false, sys::fs::mapped_file_region::readonly,
205 getLegalMapSize(Len, Offset), getLegalMapOffset(Offset), EC) {
207 const char *Start = getStart(Len, Offset);
208 init(Start, Start + Len, RequiresNullTerminator);
212 const char *getBufferIdentifier() const override {
213 // The name is stored after the class itself.
214 return reinterpret_cast<const char *>(this + 1);
217 BufferKind getBufferKind() const override {
218 return MemoryBuffer_MMap;
223 static error_code getMemoryBufferForStream(int FD,
224 StringRef BufferName,
225 std::unique_ptr<MemoryBuffer> &Result) {
226 const ssize_t ChunkSize = 4096*4;
227 SmallString<ChunkSize> Buffer;
229 // Read into Buffer until we hit EOF.
231 Buffer.reserve(Buffer.size() + ChunkSize);
232 ReadBytes = read(FD, Buffer.end(), ChunkSize);
233 if (ReadBytes == -1) {
234 if (errno == EINTR) continue;
235 return error_code(errno, posix_category());
237 Buffer.set_size(Buffer.size() + ReadBytes);
238 } while (ReadBytes != 0);
240 Result.reset(MemoryBuffer::getMemBufferCopy(Buffer, BufferName));
241 return error_code::success();
244 static error_code getFileAux(const char *Filename,
245 std::unique_ptr<MemoryBuffer> &Result,
247 bool RequiresNullTerminator,
248 bool IsVolatileSize);
250 error_code MemoryBuffer::getFile(Twine Filename,
251 std::unique_ptr<MemoryBuffer> &Result,
253 bool RequiresNullTerminator,
254 bool IsVolatileSize) {
255 // Ensure the path is null terminated.
256 SmallString<256> PathBuf;
257 StringRef NullTerminatedName = Filename.toNullTerminatedStringRef(PathBuf);
258 return getFileAux(NullTerminatedName.data(), Result, FileSize,
259 RequiresNullTerminator, IsVolatileSize);
262 error_code MemoryBuffer::getFile(Twine Filename,
263 OwningPtr<MemoryBuffer> &Result,
265 bool RequiresNullTerminator,
266 bool IsVolatileSize) {
267 std::unique_ptr<MemoryBuffer> MB;
268 error_code ec = getFile(Filename, MB, FileSize, RequiresNullTerminator,
270 Result = std::move(MB);
274 static error_code getOpenFileImpl(int FD, const char *Filename,
275 std::unique_ptr<MemoryBuffer> &Result,
276 uint64_t FileSize, uint64_t MapSize,
277 int64_t Offset, bool RequiresNullTerminator,
278 bool IsVolatileSize);
280 static error_code getFileAux(const char *Filename,
281 std::unique_ptr<MemoryBuffer> &Result, int64_t FileSize,
282 bool RequiresNullTerminator,
283 bool IsVolatileSize) {
285 error_code EC = sys::fs::openFileForRead(Filename, FD);
289 error_code ret = getOpenFileImpl(FD, Filename, Result, FileSize, FileSize, 0,
290 RequiresNullTerminator, IsVolatileSize);
295 static bool shouldUseMmap(int FD,
299 bool RequiresNullTerminator,
301 bool IsVolatileSize) {
302 // mmap may leave the buffer without null terminator if the file size changed
303 // by the time the last page is mapped in, so avoid it if the file size is
308 // We don't use mmap for small files because this can severely fragment our
310 if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize)
313 if (!RequiresNullTerminator)
317 // If we don't know the file size, use fstat to find out. fstat on an open
318 // file descriptor is cheaper than stat on a random path.
319 // FIXME: this chunk of code is duplicated, but it avoids a fstat when
320 // RequiresNullTerminator = false and MapSize != -1.
321 if (FileSize == size_t(-1)) {
322 sys::fs::file_status Status;
323 error_code EC = sys::fs::status(FD, Status);
326 FileSize = Status.getSize();
329 // If we need a null terminator and the end of the map is inside the file,
330 // we cannot use mmap.
331 size_t End = Offset + MapSize;
332 assert(End <= FileSize);
336 #if defined(_WIN32) || defined(__CYGWIN__)
337 // Don't peek the next page if file is multiple of *physical* pagesize(4k)
338 // but is not multiple of AllocationGranularity(64k),
339 // when a null terminator is required.
340 // FIXME: It's not good to hardcode 4096 here. dwPageSize shows 4096.
341 if ((FileSize & (4096 - 1)) == 0)
345 // Don't try to map files that are exactly a multiple of the system page size
346 // if we need a null terminator.
347 if ((FileSize & (PageSize -1)) == 0)
353 static error_code getOpenFileImpl(int FD, const char *Filename,
354 std::unique_ptr<MemoryBuffer> &Result,
355 uint64_t FileSize, uint64_t MapSize,
356 int64_t Offset, bool RequiresNullTerminator,
357 bool IsVolatileSize) {
358 static int PageSize = sys::process::get_self()->page_size();
360 // Default is to map the full file.
361 if (MapSize == uint64_t(-1)) {
362 // If we don't know the file size, use fstat to find out. fstat on an open
363 // file descriptor is cheaper than stat on a random path.
364 if (FileSize == uint64_t(-1)) {
365 sys::fs::file_status Status;
366 error_code EC = sys::fs::status(FD, Status);
370 // If this not a file or a block device (e.g. it's a named pipe
371 // or character device), we can't trust the size. Create the memory
372 // buffer by copying off the stream.
373 sys::fs::file_type Type = Status.type();
374 if (Type != sys::fs::file_type::regular_file &&
375 Type != sys::fs::file_type::block_file)
376 return getMemoryBufferForStream(FD, Filename, Result);
378 FileSize = Status.getSize();
383 if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
384 PageSize, IsVolatileSize)) {
386 Result.reset(new (NamedBufferAlloc(Filename)) MemoryBufferMMapFile(
387 RequiresNullTerminator, FD, MapSize, Offset, EC));
389 return error_code::success();
392 MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
394 // Failed to create a buffer. The only way it can fail is if
395 // new(std::nothrow) returns 0.
396 return make_error_code(errc::not_enough_memory);
399 std::unique_ptr<MemoryBuffer> SB(Buf);
400 char *BufPtr = const_cast<char*>(SB->getBufferStart());
402 size_t BytesLeft = MapSize;
404 if (lseek(FD, Offset, SEEK_SET) == -1)
405 return error_code(errno, posix_category());
410 ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset);
412 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
417 // Error while reading.
418 return error_code(errno, posix_category());
421 memset(BufPtr, 0, BytesLeft); // zero-initialize rest of the buffer.
424 BytesLeft -= NumRead;
429 return error_code::success();
432 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
433 std::unique_ptr<MemoryBuffer> &Result,
435 bool RequiresNullTerminator,
436 bool IsVolatileSize) {
437 return getOpenFileImpl(FD, Filename, Result, FileSize, FileSize, 0,
438 RequiresNullTerminator, IsVolatileSize);
441 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
442 OwningPtr<MemoryBuffer> &Result,
444 bool RequiresNullTerminator,
445 bool IsVolatileSize) {
446 std::unique_ptr<MemoryBuffer> MB;
447 error_code ec = getOpenFileImpl(FD, Filename, MB, FileSize, FileSize, 0,
448 RequiresNullTerminator, IsVolatileSize);
449 Result = std::move(MB);
453 error_code MemoryBuffer::getOpenFileSlice(int FD, const char *Filename,
454 std::unique_ptr<MemoryBuffer> &Result,
455 uint64_t MapSize, int64_t Offset,
456 bool IsVolatileSize) {
457 return getOpenFileImpl(FD, Filename, Result, -1, MapSize, Offset, false,
461 error_code MemoryBuffer::getOpenFileSlice(int FD, const char *Filename,
462 OwningPtr<MemoryBuffer> &Result,
463 uint64_t MapSize, int64_t Offset,
464 bool IsVolatileSize) {
465 std::unique_ptr<MemoryBuffer> MB;
466 error_code ec = getOpenFileImpl(FD, Filename, MB, -1, MapSize, Offset, false,
468 Result = std::move(MB);
472 //===----------------------------------------------------------------------===//
473 // MemoryBuffer::getSTDIN implementation.
474 //===----------------------------------------------------------------------===//
476 error_code MemoryBuffer::getSTDIN(std::unique_ptr<MemoryBuffer> &Result) {
477 // Read in all of the data from stdin, we cannot mmap stdin.
479 // FIXME: That isn't necessarily true, we should try to mmap stdin and
480 // fallback if it fails.
481 sys::ChangeStdinToBinary();
483 return getMemoryBufferForStream(0, "<stdin>", Result);
486 error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &Result) {
487 std::unique_ptr<MemoryBuffer> MB;
488 error_code ec = getSTDIN(MB);
489 Result = std::move(MB);