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/Errno.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/MathExtras.h"
20 #include "llvm/Support/Path.h"
21 #include "llvm/Support/Process.h"
22 #include "llvm/Support/Program.h"
23 #include "llvm/Support/system_error.h"
29 #include <sys/types.h>
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) {
60 memcpy(Memory, Data.data(), Data.size());
61 Memory[Data.size()] = 0; // Null terminate string.
65 struct NamedBufferAlloc {
67 NamedBufferAlloc(StringRef Name) : Name(Name) {}
71 void *operator new(size_t N, const NamedBufferAlloc &Alloc) {
72 char *Mem = static_cast<char *>(operator new(N + Alloc.Name.size() + 1));
73 CopyStringRef(Mem + N, Alloc.Name);
78 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
79 class MemoryBufferMem : public MemoryBuffer {
81 MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
82 init(InputData.begin(), InputData.end(), RequiresNullTerminator);
85 const char *getBufferIdentifier() const override {
86 // The name is stored after the class itself.
87 return reinterpret_cast<const char*>(this + 1);
90 BufferKind getBufferKind() const override {
91 return MemoryBuffer_Malloc;
96 /// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note
97 /// that InputData must be a null terminated if RequiresNullTerminator is true!
98 MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
100 bool RequiresNullTerminator) {
101 return new (NamedBufferAlloc(BufferName))
102 MemoryBufferMem(InputData, RequiresNullTerminator);
105 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
106 /// copying the contents and taking ownership of it. This has no requirements
108 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
109 StringRef BufferName) {
110 MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
111 if (!Buf) return nullptr;
112 memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
117 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
118 /// that is not initialized. Note that the caller should initialize the
119 /// memory allocated by this method. The memory is owned by the MemoryBuffer
121 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
122 StringRef BufferName) {
123 // Allocate space for the MemoryBuffer, the data and the name. It is important
124 // that MemoryBuffer and data are aligned so PointerIntPair works with them.
125 // TODO: Is 16-byte alignment enough? We copy small object files with large
126 // alignment expectations into this buffer.
127 size_t AlignedStringLen =
128 RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1, 16);
129 size_t RealLen = AlignedStringLen + Size + 1;
130 char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
131 if (!Mem) return nullptr;
133 // The name is stored after the class itself.
134 CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
136 // The buffer begins after the name and must be aligned.
137 char *Buf = Mem + AlignedStringLen;
138 Buf[Size] = 0; // Null terminate buffer.
140 return new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
143 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
144 /// is completely initialized to zeros. Note that the caller should
145 /// initialize the memory allocated by this method. The memory is owned by
146 /// the MemoryBuffer object.
147 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
148 MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
149 if (!SB) return nullptr;
150 memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
155 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
156 /// if the Filename is "-". If an error occurs, this returns null and fills
157 /// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
158 /// returns an empty buffer.
159 error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
160 std::unique_ptr<MemoryBuffer> &Result,
163 return getSTDIN(Result);
164 return getFile(Filename, Result, FileSize);
168 //===----------------------------------------------------------------------===//
169 // MemoryBuffer::getFile implementation.
170 //===----------------------------------------------------------------------===//
173 /// \brief Memory maps a file descriptor using sys::fs::mapped_file_region.
175 /// This handles converting the offset into a legal offset on the platform.
176 class MemoryBufferMMapFile : public MemoryBuffer {
177 sys::fs::mapped_file_region MFR;
179 static uint64_t getLegalMapOffset(uint64_t Offset) {
180 return Offset & ~(sys::fs::mapped_file_region::alignment() - 1);
183 static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) {
184 return Len + (Offset - getLegalMapOffset(Offset));
187 const char *getStart(uint64_t Len, uint64_t Offset) {
188 return MFR.const_data() + (Offset - getLegalMapOffset(Offset));
192 MemoryBufferMMapFile(bool RequiresNullTerminator, int FD, uint64_t Len,
193 uint64_t Offset, error_code EC)
194 : MFR(FD, false, sys::fs::mapped_file_region::readonly,
195 getLegalMapSize(Len, Offset), getLegalMapOffset(Offset), EC) {
197 const char *Start = getStart(Len, Offset);
198 init(Start, Start + Len, RequiresNullTerminator);
202 const char *getBufferIdentifier() const override {
203 // The name is stored after the class itself.
204 return reinterpret_cast<const char *>(this + 1);
207 BufferKind getBufferKind() const override {
208 return MemoryBuffer_MMap;
213 static error_code getMemoryBufferForStream(int FD,
214 StringRef BufferName,
215 std::unique_ptr<MemoryBuffer> &Result) {
216 const ssize_t ChunkSize = 4096*4;
217 SmallString<ChunkSize> Buffer;
219 // Read into Buffer until we hit EOF.
221 Buffer.reserve(Buffer.size() + ChunkSize);
222 ReadBytes = read(FD, Buffer.end(), ChunkSize);
223 if (ReadBytes == -1) {
224 if (errno == EINTR) continue;
225 return error_code(errno, generic_category());
227 Buffer.set_size(Buffer.size() + ReadBytes);
228 } while (ReadBytes != 0);
230 Result.reset(MemoryBuffer::getMemBufferCopy(Buffer, BufferName));
234 static error_code getFileAux(const char *Filename,
235 std::unique_ptr<MemoryBuffer> &Result,
237 bool RequiresNullTerminator,
238 bool IsVolatileSize);
240 error_code MemoryBuffer::getFile(Twine Filename,
241 std::unique_ptr<MemoryBuffer> &Result,
243 bool RequiresNullTerminator,
244 bool IsVolatileSize) {
245 // Ensure the path is null terminated.
246 SmallString<256> PathBuf;
247 StringRef NullTerminatedName = Filename.toNullTerminatedStringRef(PathBuf);
248 return getFileAux(NullTerminatedName.data(), Result, FileSize,
249 RequiresNullTerminator, IsVolatileSize);
252 static error_code getOpenFileImpl(int FD, const char *Filename,
253 std::unique_ptr<MemoryBuffer> &Result,
254 uint64_t FileSize, uint64_t MapSize,
255 int64_t Offset, bool RequiresNullTerminator,
256 bool IsVolatileSize);
258 static error_code getFileAux(const char *Filename,
259 std::unique_ptr<MemoryBuffer> &Result, int64_t FileSize,
260 bool RequiresNullTerminator,
261 bool IsVolatileSize) {
263 error_code EC = sys::fs::openFileForRead(Filename, FD);
267 error_code ret = getOpenFileImpl(FD, Filename, Result, FileSize, FileSize, 0,
268 RequiresNullTerminator, IsVolatileSize);
273 static bool shouldUseMmap(int FD,
277 bool RequiresNullTerminator,
279 bool IsVolatileSize) {
280 // mmap may leave the buffer without null terminator if the file size changed
281 // by the time the last page is mapped in, so avoid it if the file size is
286 // We don't use mmap for small files because this can severely fragment our
288 if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize)
291 if (!RequiresNullTerminator)
295 // If we don't know the file size, use fstat to find out. fstat on an open
296 // file descriptor is cheaper than stat on a random path.
297 // FIXME: this chunk of code is duplicated, but it avoids a fstat when
298 // RequiresNullTerminator = false and MapSize != -1.
299 if (FileSize == size_t(-1)) {
300 sys::fs::file_status Status;
301 if (sys::fs::status(FD, Status))
303 FileSize = Status.getSize();
306 // If we need a null terminator and the end of the map is inside the file,
307 // we cannot use mmap.
308 size_t End = Offset + MapSize;
309 assert(End <= FileSize);
313 // Don't try to map files that are exactly a multiple of the system page size
314 // if we need a null terminator.
315 if ((FileSize & (PageSize -1)) == 0)
321 static error_code getOpenFileImpl(int FD, const char *Filename,
322 std::unique_ptr<MemoryBuffer> &Result,
323 uint64_t FileSize, uint64_t MapSize,
324 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 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, Result);
346 FileSize = Status.getSize();
351 if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
352 PageSize, IsVolatileSize)) {
354 Result.reset(new (NamedBufferAlloc(Filename)) MemoryBufferMMapFile(
355 RequiresNullTerminator, FD, MapSize, Offset, EC));
360 MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
362 // Failed to create a buffer. The only way it can fail is if
363 // new(std::nothrow) returns 0.
364 return make_error_code(errc::not_enough_memory);
367 std::unique_ptr<MemoryBuffer> SB(Buf);
368 char *BufPtr = const_cast<char*>(SB->getBufferStart());
370 size_t BytesLeft = MapSize;
372 if (lseek(FD, Offset, SEEK_SET) == -1)
373 return error_code(errno, generic_category());
378 ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset);
380 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
385 // Error while reading.
386 return error_code(errno, generic_category());
389 memset(BufPtr, 0, BytesLeft); // zero-initialize rest of the buffer.
392 BytesLeft -= NumRead;
400 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
401 std::unique_ptr<MemoryBuffer> &Result,
403 bool RequiresNullTerminator,
404 bool IsVolatileSize) {
405 return getOpenFileImpl(FD, Filename, Result, FileSize, FileSize, 0,
406 RequiresNullTerminator, IsVolatileSize);
409 error_code MemoryBuffer::getOpenFileSlice(int FD, const char *Filename,
410 std::unique_ptr<MemoryBuffer> &Result,
411 uint64_t MapSize, int64_t Offset,
412 bool IsVolatileSize) {
413 return getOpenFileImpl(FD, Filename, Result, -1, MapSize, Offset, false,
417 //===----------------------------------------------------------------------===//
418 // MemoryBuffer::getSTDIN implementation.
419 //===----------------------------------------------------------------------===//
421 error_code MemoryBuffer::getSTDIN(std::unique_ptr<MemoryBuffer> &Result) {
422 // Read in all of the data from stdin, we cannot mmap stdin.
424 // FIXME: That isn't necessarily true, we should try to mmap stdin and
425 // fallback if it fails.
426 sys::ChangeStdinToBinary();
428 return getMemoryBufferForStream(0, "<stdin>", Result);