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 assert(BufEnd[0] == 0 && "Buffer is not null terminated!");
51 BufferStart = BufStart;
55 //===----------------------------------------------------------------------===//
56 // MemoryBufferMem implementation.
57 //===----------------------------------------------------------------------===//
59 /// CopyStringRef - Copies contents of a StringRef into a block of memory and
60 /// null-terminates it.
61 static void CopyStringRef(char *Memory, StringRef Data) {
62 memcpy(Memory, Data.data(), Data.size());
63 Memory[Data.size()] = 0; // Null terminate string.
66 /// GetNamedBuffer - Allocates a new MemoryBuffer with Name copied after it.
68 static T* GetNamedBuffer(StringRef Buffer, StringRef Name) {
69 char *Mem = static_cast<char*>(operator new(sizeof(T) + Name.size() + 1));
70 CopyStringRef(Mem + sizeof(T), Name);
71 return new (Mem) T(Buffer);
75 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
76 class MemoryBufferMem : public MemoryBuffer {
78 MemoryBufferMem(StringRef InputData) {
79 init(InputData.begin(), InputData.end());
82 virtual const char *getBufferIdentifier() const {
83 // The name is stored after the class itself.
84 return reinterpret_cast<const char*>(this + 1);
89 /// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note
90 /// that EndPtr[0] must be a null byte and be accessible!
91 MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
92 StringRef BufferName) {
93 return GetNamedBuffer<MemoryBufferMem>(InputData, BufferName);
96 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
97 /// copying the contents and taking ownership of it. This has no requirements
99 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
100 StringRef BufferName) {
101 MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
103 memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
108 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
109 /// that is not initialized. Note that the caller should initialize the
110 /// memory allocated by this method. The memory is owned by the MemoryBuffer
112 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
113 StringRef BufferName) {
114 // Allocate space for the MemoryBuffer, the data and the name. It is important
115 // that MemoryBuffer and data are aligned so PointerIntPair works with them.
116 size_t AlignedStringLen =
117 RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1,
118 sizeof(void*)); // TODO: Is sizeof(void*) enough?
119 size_t RealLen = AlignedStringLen + Size + 1;
120 char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
123 // The name is stored after the class itself.
124 CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
126 // The buffer begins after the name and must be aligned.
127 char *Buf = Mem + AlignedStringLen;
128 Buf[Size] = 0; // Null terminate buffer.
130 return new (Mem) MemoryBufferMem(StringRef(Buf, Size));
133 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
134 /// is completely initialized to zeros. Note that the caller should
135 /// initialize the memory allocated by this method. The memory is owned by
136 /// the MemoryBuffer object.
137 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
138 MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
140 memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
145 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
146 /// if the Filename is "-". If an error occurs, this returns null and fills
147 /// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
148 /// returns an empty buffer.
149 error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
150 OwningPtr<MemoryBuffer> &result,
153 return getSTDIN(result);
154 return getFile(Filename, result, FileSize);
157 error_code MemoryBuffer::getFileOrSTDIN(const char *Filename,
158 OwningPtr<MemoryBuffer> &result,
160 if (strcmp(Filename, "-") == 0)
161 return getSTDIN(result);
162 return getFile(Filename, result, FileSize);
165 //===----------------------------------------------------------------------===//
166 // MemoryBuffer::getFile implementation.
167 //===----------------------------------------------------------------------===//
170 /// MemoryBufferMMapFile - This represents a file that was mapped in with the
171 /// sys::Path::MapInFilePages method. When destroyed, it calls the
172 /// sys::Path::UnMapFilePages method.
173 class MemoryBufferMMapFile : public MemoryBufferMem {
175 MemoryBufferMMapFile(StringRef Buffer)
176 : MemoryBufferMem(Buffer) { }
178 ~MemoryBufferMMapFile() {
179 sys::Path::UnMapFilePages(getBufferStart(), getBufferSize());
184 error_code MemoryBuffer::getFile(StringRef Filename,
185 OwningPtr<MemoryBuffer> &result,
187 // Ensure the path is null terminated.
188 SmallString<256> PathBuf(Filename.begin(), Filename.end());
189 return MemoryBuffer::getFile(PathBuf.c_str(), result, FileSize);
192 error_code MemoryBuffer::getFile(const char *Filename,
193 OwningPtr<MemoryBuffer> &result,
195 int OpenFlags = O_RDONLY;
197 OpenFlags |= O_BINARY; // Open input file in binary mode on win32.
199 int FD = ::open(Filename, OpenFlags);
201 return error_code(errno, posix_category());
203 error_code ret = getOpenFile(FD, Filename, result, FileSize);
208 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
209 OwningPtr<MemoryBuffer> &result,
211 // If we don't know the file size, use fstat to find out. fstat on an open
212 // file descriptor is cheaper than stat on a random path.
213 if (FileSize == -1) {
214 struct stat FileInfo;
215 // TODO: This should use fstat64 when available.
216 if (fstat(FD, &FileInfo) == -1) {
217 return error_code(errno, posix_category());
219 FileSize = FileInfo.st_size;
223 // If the file is large, try to use mmap to read it in. We don't use mmap
224 // for small files, because this can severely fragment our address space. Also
225 // don't try to map files that are exactly a multiple of the system page size,
226 // as the file would not have the required null terminator.
228 // FIXME: Can we just mmap an extra page in the latter case?
229 if (FileSize >= 4096*4 &&
230 (FileSize & (sys::Process::GetPageSize()-1)) != 0) {
231 if (const char *Pages = sys::Path::MapInFilePages(FD, FileSize)) {
232 result.reset(GetNamedBuffer<MemoryBufferMMapFile>(
233 StringRef(Pages, FileSize), Filename));
238 MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(FileSize, Filename);
240 // Failed to create a buffer. The only way it can fail is if
241 // new(std::nothrow) returns 0.
242 return make_error_code(errc::not_enough_memory);
245 OwningPtr<MemoryBuffer> SB(Buf);
246 char *BufPtr = const_cast<char*>(SB->getBufferStart());
248 size_t BytesLeft = FileSize;
250 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
254 // Error while reading.
255 return error_code(errno, posix_category());
256 } else if (NumRead == 0) {
257 // We hit EOF early, truncate and terminate buffer.
258 Buf->BufferEnd = BufPtr;
263 BytesLeft -= NumRead;
271 //===----------------------------------------------------------------------===//
272 // MemoryBuffer::getSTDIN implementation.
273 //===----------------------------------------------------------------------===//
275 error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &result) {
276 // Read in all of the data from stdin, we cannot mmap stdin.
278 // FIXME: That isn't necessarily true, we should try to mmap stdin and
279 // fallback if it fails.
280 sys::Program::ChangeStdinToBinary();
282 const ssize_t ChunkSize = 4096*4;
283 SmallString<ChunkSize> Buffer;
285 // Read into Buffer until we hit EOF.
287 Buffer.reserve(Buffer.size() + ChunkSize);
288 ReadBytes = read(0, Buffer.end(), ChunkSize);
289 if (ReadBytes == -1) {
290 if (errno == EINTR) continue;
291 return error_code(errno, posix_category());
293 Buffer.set_size(Buffer.size() + ReadBytes);
294 } while (ReadBytes != 0);
296 result.reset(getMemBufferCopy(Buffer, "<stdin>"));