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"
28 #include <sys/types.h>
29 #include <system_error>
30 #if !defined(_MSC_VER) && !defined(__MINGW32__)
36 using std::error_code;
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);
169 //===----------------------------------------------------------------------===//
170 // MemoryBuffer::getFile implementation.
171 //===----------------------------------------------------------------------===//
174 /// \brief Memory maps a file descriptor using sys::fs::mapped_file_region.
176 /// This handles converting the offset into a legal offset on the platform.
177 class MemoryBufferMMapFile : public MemoryBuffer {
178 sys::fs::mapped_file_region MFR;
180 static uint64_t getLegalMapOffset(uint64_t Offset) {
181 return Offset & ~(sys::fs::mapped_file_region::alignment() - 1);
184 static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) {
185 return Len + (Offset - getLegalMapOffset(Offset));
188 const char *getStart(uint64_t Len, uint64_t Offset) {
189 return MFR.const_data() + (Offset - getLegalMapOffset(Offset));
193 MemoryBufferMMapFile(bool RequiresNullTerminator, int FD, uint64_t Len,
194 uint64_t Offset, error_code EC)
195 : MFR(FD, false, sys::fs::mapped_file_region::readonly,
196 getLegalMapSize(Len, Offset), getLegalMapOffset(Offset), EC) {
198 const char *Start = getStart(Len, Offset);
199 init(Start, Start + Len, RequiresNullTerminator);
203 const char *getBufferIdentifier() const override {
204 // The name is stored after the class itself.
205 return reinterpret_cast<const char *>(this + 1);
208 BufferKind getBufferKind() const override {
209 return MemoryBuffer_MMap;
214 static error_code getMemoryBufferForStream(int FD,
215 StringRef BufferName,
216 std::unique_ptr<MemoryBuffer> &Result) {
217 const ssize_t ChunkSize = 4096*4;
218 SmallString<ChunkSize> Buffer;
220 // Read into Buffer until we hit EOF.
222 Buffer.reserve(Buffer.size() + ChunkSize);
223 ReadBytes = read(FD, Buffer.end(), ChunkSize);
224 if (ReadBytes == -1) {
225 if (errno == EINTR) continue;
226 return error_code(errno, std::generic_category());
228 Buffer.set_size(Buffer.size() + ReadBytes);
229 } while (ReadBytes != 0);
231 Result.reset(MemoryBuffer::getMemBufferCopy(Buffer, BufferName));
235 static error_code getFileAux(const char *Filename,
236 std::unique_ptr<MemoryBuffer> &Result,
238 bool RequiresNullTerminator,
239 bool IsVolatileSize);
241 error_code MemoryBuffer::getFile(Twine Filename,
242 std::unique_ptr<MemoryBuffer> &Result,
244 bool RequiresNullTerminator,
245 bool IsVolatileSize) {
246 // Ensure the path is null terminated.
247 SmallString<256> PathBuf;
248 StringRef NullTerminatedName = Filename.toNullTerminatedStringRef(PathBuf);
249 return getFileAux(NullTerminatedName.data(), Result, FileSize,
250 RequiresNullTerminator, IsVolatileSize);
253 static error_code getOpenFileImpl(int FD, const char *Filename,
254 std::unique_ptr<MemoryBuffer> &Result,
255 uint64_t FileSize, uint64_t MapSize,
256 int64_t Offset, bool RequiresNullTerminator,
257 bool IsVolatileSize);
259 static error_code getFileAux(const char *Filename,
260 std::unique_ptr<MemoryBuffer> &Result, int64_t FileSize,
261 bool RequiresNullTerminator,
262 bool IsVolatileSize) {
264 error_code EC = sys::fs::openFileForRead(Filename, FD);
268 error_code ret = getOpenFileImpl(FD, Filename, Result, FileSize, FileSize, 0,
269 RequiresNullTerminator, IsVolatileSize);
274 static bool shouldUseMmap(int FD,
278 bool RequiresNullTerminator,
280 bool IsVolatileSize) {
281 // mmap may leave the buffer without null terminator if the file size changed
282 // by the time the last page is mapped in, so avoid it if the file size is
287 // We don't use mmap for small files because this can severely fragment our
289 if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize)
292 if (!RequiresNullTerminator)
296 // If we don't know the file size, use fstat to find out. fstat on an open
297 // file descriptor is cheaper than stat on a random path.
298 // FIXME: this chunk of code is duplicated, but it avoids a fstat when
299 // RequiresNullTerminator = false and MapSize != -1.
300 if (FileSize == size_t(-1)) {
301 sys::fs::file_status Status;
302 if (sys::fs::status(FD, Status))
304 FileSize = Status.getSize();
307 // If we need a null terminator and the end of the map is inside the file,
308 // we cannot use mmap.
309 size_t End = Offset + MapSize;
310 assert(End <= FileSize);
314 // Don't try to map files that are exactly a multiple of the system page size
315 // if we need a null terminator.
316 if ((FileSize & (PageSize -1)) == 0)
322 static error_code getOpenFileImpl(int FD, const char *Filename,
323 std::unique_ptr<MemoryBuffer> &Result,
324 uint64_t FileSize, uint64_t MapSize,
325 int64_t Offset, bool RequiresNullTerminator,
326 bool IsVolatileSize) {
327 static int PageSize = sys::process::get_self()->page_size();
329 // Default is to map the full file.
330 if (MapSize == uint64_t(-1)) {
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 if (FileSize == uint64_t(-1)) {
334 sys::fs::file_status Status;
335 error_code EC = sys::fs::status(FD, Status);
339 // If this not a file or a block device (e.g. it's a named pipe
340 // or character device), we can't trust the size. Create the memory
341 // buffer by copying off the stream.
342 sys::fs::file_type Type = Status.type();
343 if (Type != sys::fs::file_type::regular_file &&
344 Type != sys::fs::file_type::block_file)
345 return getMemoryBufferForStream(FD, Filename, Result);
347 FileSize = Status.getSize();
352 if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
353 PageSize, IsVolatileSize)) {
355 Result.reset(new (NamedBufferAlloc(Filename)) MemoryBufferMMapFile(
356 RequiresNullTerminator, FD, MapSize, Offset, EC));
361 MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
363 // Failed to create a buffer. The only way it can fail is if
364 // new(std::nothrow) returns 0.
365 return std::make_error_code(std::errc::not_enough_memory);
368 std::unique_ptr<MemoryBuffer> SB(Buf);
369 char *BufPtr = const_cast<char*>(SB->getBufferStart());
371 size_t BytesLeft = MapSize;
373 if (lseek(FD, Offset, SEEK_SET) == -1)
374 return 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 error_code(errno, std::generic_category());
390 memset(BufPtr, 0, BytesLeft); // zero-initialize rest of the buffer.
393 BytesLeft -= NumRead;
401 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
402 std::unique_ptr<MemoryBuffer> &Result,
404 bool RequiresNullTerminator,
405 bool IsVolatileSize) {
406 return getOpenFileImpl(FD, Filename, Result, FileSize, FileSize, 0,
407 RequiresNullTerminator, IsVolatileSize);
410 error_code MemoryBuffer::getOpenFileSlice(int FD, const char *Filename,
411 std::unique_ptr<MemoryBuffer> &Result,
412 uint64_t MapSize, int64_t Offset,
413 bool IsVolatileSize) {
414 return getOpenFileImpl(FD, Filename, Result, -1, MapSize, Offset, false,
418 //===----------------------------------------------------------------------===//
419 // MemoryBuffer::getSTDIN implementation.
420 //===----------------------------------------------------------------------===//
422 error_code MemoryBuffer::getSTDIN(std::unique_ptr<MemoryBuffer> &Result) {
423 // Read in all of the data from stdin, we cannot mmap stdin.
425 // FIXME: That isn't necessarily true, we should try to mmap stdin and
426 // fallback if it fails.
427 sys::ChangeStdinToBinary();
429 return getMemoryBufferForStream(0, "<stdin>", Result);