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((BufEnd[0] == 0 || !RequiresNullTerminator) &&
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,
95 StringRef BufferName) {
96 return GetNamedBuffer<MemoryBufferMem>(InputData, BufferName, true);
99 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
100 /// copying the contents and taking ownership of it. This has no requirements
102 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
103 StringRef BufferName) {
104 MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
106 memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
111 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
112 /// that is not initialized. Note that the caller should initialize the
113 /// memory allocated by this method. The memory is owned by the MemoryBuffer
115 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
116 StringRef BufferName) {
117 // Allocate space for the MemoryBuffer, the data and the name. It is important
118 // that MemoryBuffer and data are aligned so PointerIntPair works with them.
119 size_t AlignedStringLen =
120 RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1,
121 sizeof(void*)); // TODO: Is sizeof(void*) enough?
122 size_t RealLen = AlignedStringLen + Size + 1;
123 char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
126 // The name is stored after the class itself.
127 CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
129 // The buffer begins after the name and must be aligned.
130 char *Buf = Mem + AlignedStringLen;
131 Buf[Size] = 0; // Null terminate buffer.
133 return new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
136 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
137 /// is completely initialized to zeros. Note that the caller should
138 /// initialize the memory allocated by this method. The memory is owned by
139 /// the MemoryBuffer object.
140 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
141 MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
143 memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
148 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
149 /// if the Filename is "-". If an error occurs, this returns null and fills
150 /// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
151 /// returns an empty buffer.
152 error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
153 OwningPtr<MemoryBuffer> &result,
156 return getSTDIN(result);
157 return getFile(Filename, result, FileSize);
160 error_code MemoryBuffer::getFileOrSTDIN(const char *Filename,
161 OwningPtr<MemoryBuffer> &result,
163 if (strcmp(Filename, "-") == 0)
164 return getSTDIN(result);
165 return getFile(Filename, result, FileSize);
168 //===----------------------------------------------------------------------===//
169 // MemoryBuffer::getFile implementation.
170 //===----------------------------------------------------------------------===//
173 /// MemoryBufferMMapFile - This represents a file that was mapped in with the
174 /// sys::Path::MapInFilePages method. When destroyed, it calls the
175 /// sys::Path::UnMapFilePages method.
176 class MemoryBufferMMapFile : public MemoryBufferMem {
178 MemoryBufferMMapFile(StringRef Buffer, bool RequiresNullTerminator)
179 : MemoryBufferMem(Buffer, RequiresNullTerminator) { }
181 ~MemoryBufferMMapFile() {
182 static int PageSize = sys::Process::GetPageSize();
184 uintptr_t Start = reinterpret_cast<uintptr_t>(getBufferStart());
185 size_t Size = getBufferSize();
186 uintptr_t RealStart = Start & ~(PageSize - 1);
187 size_t RealSize = Size + (Start - RealStart);
189 sys::Path::UnMapFilePages(reinterpret_cast<const char*>(RealStart),
195 error_code MemoryBuffer::getFile(StringRef Filename,
196 OwningPtr<MemoryBuffer> &result,
198 // Ensure the path is null terminated.
199 SmallString<256> PathBuf(Filename.begin(), Filename.end());
200 return MemoryBuffer::getFile(PathBuf.c_str(), result, FileSize);
203 error_code MemoryBuffer::getFile(const char *Filename,
204 OwningPtr<MemoryBuffer> &result,
206 int OpenFlags = O_RDONLY;
208 OpenFlags |= O_BINARY; // Open input file in binary mode on win32.
210 int FD = ::open(Filename, OpenFlags);
212 return error_code(errno, posix_category());
214 error_code ret = getOpenFile(FD, Filename, result, FileSize);
219 static bool shouldUseMmap(size_t FileSize,
222 bool RequiresNullTerminator,
224 // We don't use mmap for small files because this can severely fragment our
226 if (MapSize < 4096*4)
229 if (!RequiresNullTerminator)
232 // If we need a null terminator and the end of the map is inside the file,
233 // we cannot use mmap.
234 size_t End = Offset + MapSize;
235 assert(End <= FileSize);
239 // Don't try to map files that are exactly a multiple of the system page size
240 // if we need a null terminator.
241 if ((FileSize & (PageSize -1)) == 0)
247 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
248 OwningPtr<MemoryBuffer> &result,
249 size_t FileSize, size_t MapSize,
251 bool RequiresNullTerminator) {
252 static int PageSize = sys::Process::GetPageSize();
254 // If we don't know the file size, use fstat to find out. fstat on an open
255 // file descriptor is cheaper than stat on a random path.
256 if (FileSize == size_t(-1)) {
257 struct stat FileInfo;
258 // TODO: This should use fstat64 when available.
259 if (fstat(FD, &FileInfo) == -1) {
260 return error_code(errno, posix_category());
262 FileSize = FileInfo.st_size;
265 // Default is to map the full file.
266 if (MapSize == size_t(-1))
269 if (shouldUseMmap(FileSize, MapSize, Offset, RequiresNullTerminator,
271 off_t RealMapOffset = Offset & ~(PageSize - 1);
272 off_t Delta = Offset - RealMapOffset;
273 size_t RealMapSize = MapSize + Delta;
275 if (const char *Pages = sys::Path::MapInFilePages(FD,
278 result.reset(GetNamedBuffer<MemoryBufferMMapFile>(
279 StringRef(Pages + Delta, MapSize), Filename, RequiresNullTerminator));
284 MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
286 // Failed to create a buffer. The only way it can fail is if
287 // new(std::nothrow) returns 0.
288 return make_error_code(errc::not_enough_memory);
291 OwningPtr<MemoryBuffer> SB(Buf);
292 char *BufPtr = const_cast<char*>(SB->getBufferStart());
294 size_t BytesLeft = MapSize;
295 if (lseek(FD, Offset, SEEK_SET) == -1)
296 return error_code(errno, posix_category());
299 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
303 // Error while reading.
304 return error_code(errno, posix_category());
305 } else if (NumRead == 0) {
306 // We hit EOF early, truncate and terminate buffer.
307 Buf->BufferEnd = BufPtr;
312 BytesLeft -= NumRead;
320 //===----------------------------------------------------------------------===//
321 // MemoryBuffer::getSTDIN implementation.
322 //===----------------------------------------------------------------------===//
324 error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &result) {
325 // Read in all of the data from stdin, we cannot mmap stdin.
327 // FIXME: That isn't necessarily true, we should try to mmap stdin and
328 // fallback if it fails.
329 sys::Program::ChangeStdinToBinary();
331 const ssize_t ChunkSize = 4096*4;
332 SmallString<ChunkSize> Buffer;
334 // Read into Buffer until we hit EOF.
336 Buffer.reserve(Buffer.size() + ChunkSize);
337 ReadBytes = read(0, Buffer.end(), ChunkSize);
338 if (ReadBytes == -1) {
339 if (errno == EINTR) continue;
340 return error_code(errno, posix_category());
342 Buffer.set_size(Buffer.size() + ReadBytes);
343 } while (ReadBytes != 0);
345 result.reset(getMemBufferCopy(Buffer, "<stdin>"));