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/Support/MathExtras.h"
18 #include "llvm/Support/Errno.h"
19 #include "llvm/Support/Path.h"
20 #include "llvm/Support/Process.h"
21 #include "llvm/Support/Program.h"
22 #include "llvm/Support/system_error.h"
28 #include <sys/types.h>
30 #if !defined(_MSC_VER) && !defined(__MINGW32__)
39 namespace { const llvm::error_code success; }
41 //===----------------------------------------------------------------------===//
42 // MemoryBuffer implementation itself.
43 //===----------------------------------------------------------------------===//
45 MemoryBuffer::~MemoryBuffer() { }
47 /// init - Initialize this MemoryBuffer as a reference to externally allocated
48 /// memory, memory that we know is already null terminated.
49 void MemoryBuffer::init(const char *BufStart, const char *BufEnd,
50 bool RequiresNullTerminator) {
51 assert((!RequiresNullTerminator || BufEnd[0] == 0) &&
52 "Buffer is not null terminated!");
53 BufferStart = BufStart;
57 //===----------------------------------------------------------------------===//
58 // MemoryBufferMem implementation.
59 //===----------------------------------------------------------------------===//
61 /// CopyStringRef - Copies contents of a StringRef into a block of memory and
62 /// null-terminates it.
63 static void CopyStringRef(char *Memory, StringRef Data) {
64 memcpy(Memory, Data.data(), Data.size());
65 Memory[Data.size()] = 0; // Null terminate string.
68 /// GetNamedBuffer - Allocates a new MemoryBuffer with Name copied after it.
70 static T* GetNamedBuffer(StringRef Buffer, StringRef Name,
71 bool RequiresNullTerminator) {
72 char *Mem = static_cast<char*>(operator new(sizeof(T) + Name.size() + 1));
73 CopyStringRef(Mem + sizeof(T), Name);
74 return new (Mem) T(Buffer, RequiresNullTerminator);
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 virtual const char *getBufferIdentifier() const {
86 // The name is stored after the class itself.
87 return reinterpret_cast<const char*>(this + 1);
92 /// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note
93 /// that EndPtr[0] must be a null byte and be accessible!
94 MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
96 bool RequiresNullTerminator) {
97 return GetNamedBuffer<MemoryBufferMem>(InputData, BufferName,
98 RequiresNullTerminator);
101 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
102 /// copying the contents and taking ownership of it. This has no requirements
104 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
105 StringRef BufferName) {
106 MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
108 memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
113 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
114 /// that is not initialized. Note that the caller should initialize the
115 /// memory allocated by this method. The memory is owned by the MemoryBuffer
117 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
118 StringRef BufferName) {
119 // Allocate space for the MemoryBuffer, the data and the name. It is important
120 // that MemoryBuffer and data are aligned so PointerIntPair works with them.
121 size_t AlignedStringLen =
122 RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1,
123 sizeof(void*)); // TODO: Is sizeof(void*) enough?
124 size_t RealLen = AlignedStringLen + Size + 1;
125 char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
128 // The name is stored after the class itself.
129 CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
131 // The buffer begins after the name and must be aligned.
132 char *Buf = Mem + AlignedStringLen;
133 Buf[Size] = 0; // Null terminate buffer.
135 return new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
138 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
139 /// is completely initialized to zeros. Note that the caller should
140 /// initialize the memory allocated by this method. The memory is owned by
141 /// the MemoryBuffer object.
142 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
143 MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
145 memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
150 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
151 /// if the Filename is "-". If an error occurs, this returns null and fills
152 /// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
153 /// returns an empty buffer.
154 error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
155 OwningPtr<MemoryBuffer> &result,
158 return getSTDIN(result);
159 return getFile(Filename, result, FileSize);
162 error_code MemoryBuffer::getFileOrSTDIN(const char *Filename,
163 OwningPtr<MemoryBuffer> &result,
165 if (strcmp(Filename, "-") == 0)
166 return getSTDIN(result);
167 return getFile(Filename, result, FileSize);
170 //===----------------------------------------------------------------------===//
171 // MemoryBuffer::getFile implementation.
172 //===----------------------------------------------------------------------===//
175 /// MemoryBufferMMapFile - This represents a file that was mapped in with the
176 /// sys::Path::MapInFilePages method. When destroyed, it calls the
177 /// sys::Path::UnMapFilePages method.
178 class MemoryBufferMMapFile : public MemoryBufferMem {
180 MemoryBufferMMapFile(StringRef Buffer, bool RequiresNullTerminator)
181 : MemoryBufferMem(Buffer, RequiresNullTerminator) { }
183 ~MemoryBufferMMapFile() {
184 static int PageSize = sys::Process::GetPageSize();
186 uintptr_t Start = reinterpret_cast<uintptr_t>(getBufferStart());
187 size_t Size = getBufferSize();
188 uintptr_t RealStart = Start & ~(PageSize - 1);
189 size_t RealSize = Size + (Start - RealStart);
191 sys::Path::UnMapFilePages(reinterpret_cast<const char*>(RealStart),
197 error_code MemoryBuffer::getFile(StringRef Filename,
198 OwningPtr<MemoryBuffer> &result,
200 // Ensure the path is null terminated.
201 SmallString<256> PathBuf(Filename.begin(), Filename.end());
202 return MemoryBuffer::getFile(PathBuf.c_str(), result, FileSize);
205 error_code MemoryBuffer::getFile(const char *Filename,
206 OwningPtr<MemoryBuffer> &result,
208 int OpenFlags = O_RDONLY;
210 OpenFlags |= O_BINARY; // Open input file in binary mode on win32.
212 int FD = ::open(Filename, OpenFlags);
214 return error_code(errno, posix_category());
216 error_code ret = getOpenFile(FD, Filename, result, FileSize);
221 static bool shouldUseMmap(int FD,
225 bool RequiresNullTerminator,
227 // We don't use mmap for small files because this can severely fragment our
229 if (MapSize < 4096*4)
232 if (!RequiresNullTerminator)
236 // If we don't know the file size, use fstat to find out. fstat on an open
237 // file descriptor is cheaper than stat on a random path.
238 // FIXME: this chunk of code is duplicated, but it avoids a fstat when
239 // RequiresNullTerminator = false and MapSize != -1.
240 if (FileSize == size_t(-1)) {
241 struct stat FileInfo;
242 // TODO: This should use fstat64 when available.
243 if (fstat(FD, &FileInfo) == -1) {
244 return error_code(errno, posix_category());
246 FileSize = FileInfo.st_size;
249 // If we need a null terminator and the end of the map is inside the file,
250 // we cannot use mmap.
251 size_t End = Offset + MapSize;
252 assert(End <= FileSize);
256 // Don't try to map files that are exactly a multiple of the system page size
257 // if we need a null terminator.
258 if ((FileSize & (PageSize -1)) == 0)
264 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
265 OwningPtr<MemoryBuffer> &result,
266 size_t FileSize, size_t MapSize,
268 bool RequiresNullTerminator) {
269 static int PageSize = sys::Process::GetPageSize();
271 // Default is to map the full file.
272 if (MapSize == size_t(-1)) {
273 // If we don't know the file size, use fstat to find out. fstat on an open
274 // file descriptor is cheaper than stat on a random path.
275 if (FileSize == size_t(-1)) {
276 struct stat FileInfo;
277 // TODO: This should use fstat64 when available.
278 if (fstat(FD, &FileInfo) == -1) {
279 return error_code(errno, posix_category());
281 FileSize = FileInfo.st_size;
286 if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
288 off_t RealMapOffset = Offset & ~(PageSize - 1);
289 off_t Delta = Offset - RealMapOffset;
290 size_t RealMapSize = MapSize + Delta;
292 if (const char *Pages = sys::Path::MapInFilePages(FD,
295 result.reset(GetNamedBuffer<MemoryBufferMMapFile>(
296 StringRef(Pages + Delta, MapSize), Filename, RequiresNullTerminator));
301 MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
303 // Failed to create a buffer. The only way it can fail is if
304 // new(std::nothrow) returns 0.
305 return make_error_code(errc::not_enough_memory);
308 OwningPtr<MemoryBuffer> SB(Buf);
309 char *BufPtr = const_cast<char*>(SB->getBufferStart());
311 size_t BytesLeft = MapSize;
312 if (lseek(FD, Offset, SEEK_SET) == -1)
313 return error_code(errno, posix_category());
316 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
320 // Error while reading.
321 return error_code(errno, posix_category());
322 } else if (NumRead == 0) {
323 // We hit EOF early, truncate and terminate buffer.
324 Buf->BufferEnd = BufPtr;
329 BytesLeft -= NumRead;
337 //===----------------------------------------------------------------------===//
338 // MemoryBuffer::getSTDIN implementation.
339 //===----------------------------------------------------------------------===//
341 error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &result) {
342 // Read in all of the data from stdin, we cannot mmap stdin.
344 // FIXME: That isn't necessarily true, we should try to mmap stdin and
345 // fallback if it fails.
346 sys::Program::ChangeStdinToBinary();
348 const ssize_t ChunkSize = 4096*4;
349 SmallString<ChunkSize> Buffer;
351 // Read into Buffer until we hit EOF.
353 Buffer.reserve(Buffer.size() + ChunkSize);
354 ReadBytes = read(0, Buffer.end(), ChunkSize);
355 if (ReadBytes == -1) {
356 if (errno == EINTR) continue;
357 return error_code(errno, posix_category());
359 Buffer.set_size(Buffer.size() + ReadBytes);
360 } while (ReadBytes != 0);
362 result.reset(getMemBufferCopy(Buffer, "<stdin>"));