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"
27 #include <sys/types.h>
29 #if !defined(_MSC_VER) && !defined(__MINGW32__)
38 namespace { const llvm::error_code success; }
40 //===----------------------------------------------------------------------===//
41 // MemoryBuffer implementation itself.
42 //===----------------------------------------------------------------------===//
44 MemoryBuffer::~MemoryBuffer() { }
46 /// init - Initialize this MemoryBuffer as a reference to externally allocated
47 /// memory, memory that we know is already null terminated.
48 void MemoryBuffer::init(const char *BufStart, const char *BufEnd) {
49 assert(BufEnd[0] == 0 && "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.
65 /// GetNamedBuffer - Allocates a new MemoryBuffer with Name copied after it.
67 static T* GetNamedBuffer(StringRef Buffer, StringRef Name) {
68 char *Mem = static_cast<char*>(operator new(sizeof(T) + Name.size() + 1));
69 CopyStringRef(Mem + sizeof(T), Name);
70 return new (Mem) T(Buffer);
74 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
75 class MemoryBufferMem : public MemoryBuffer {
77 MemoryBufferMem(StringRef InputData) {
78 init(InputData.begin(), InputData.end());
81 virtual const char *getBufferIdentifier() const {
82 // The name is stored after the class itself.
83 return reinterpret_cast<const char*>(this + 1);
88 /// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note
89 /// that EndPtr[0] must be a null byte and be accessible!
90 MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
91 StringRef BufferName) {
92 return GetNamedBuffer<MemoryBufferMem>(InputData, BufferName);
95 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
96 /// copying the contents and taking ownership of it. This has no requirements
98 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
99 StringRef BufferName) {
100 MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
102 memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
107 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
108 /// that is not initialized. Note that the caller should initialize the
109 /// memory allocated by this method. The memory is owned by the MemoryBuffer
111 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
112 StringRef BufferName) {
113 // Allocate space for the MemoryBuffer, the data and the name. It is important
114 // that MemoryBuffer and data are aligned so PointerIntPair works with them.
115 size_t AlignedStringLen =
116 RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1,
117 sizeof(void*)); // TODO: Is sizeof(void*) enough?
118 size_t RealLen = AlignedStringLen + Size + 1;
119 char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
122 // The name is stored after the class itself.
123 CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
125 // The buffer begins after the name and must be aligned.
126 char *Buf = Mem + AlignedStringLen;
127 Buf[Size] = 0; // Null terminate buffer.
129 return new (Mem) MemoryBufferMem(StringRef(Buf, Size));
132 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
133 /// is completely initialized to zeros. Note that the caller should
134 /// initialize the memory allocated by this method. The memory is owned by
135 /// the MemoryBuffer object.
136 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
137 MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
139 memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
144 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
145 /// if the Filename is "-". If an error occurs, this returns null and fills
146 /// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
147 /// returns an empty buffer.
148 error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
149 OwningPtr<MemoryBuffer> &result,
152 return getSTDIN(result);
153 return getFile(Filename, result, FileSize);
156 error_code MemoryBuffer::getFileOrSTDIN(const char *Filename,
157 OwningPtr<MemoryBuffer> &result,
159 if (strcmp(Filename, "-") == 0)
160 return getSTDIN(result);
161 return getFile(Filename, result, FileSize);
164 //===----------------------------------------------------------------------===//
165 // MemoryBuffer::getFile implementation.
166 //===----------------------------------------------------------------------===//
169 /// MemoryBufferMMapFile - This represents a file that was mapped in with the
170 /// sys::Path::MapInFilePages method. When destroyed, it calls the
171 /// sys::Path::UnMapFilePages method.
172 class MemoryBufferMMapFile : public MemoryBufferMem {
174 MemoryBufferMMapFile(StringRef Buffer)
175 : MemoryBufferMem(Buffer) { }
177 ~MemoryBufferMMapFile() {
178 sys::Path::UnMapFilePages(getBufferStart(), getBufferSize());
182 /// FileCloser - RAII object to make sure an FD gets closed properly.
186 explicit FileCloser(int FD) : FD(FD) {}
187 ~FileCloser() { ::close(FD); }
191 error_code MemoryBuffer::getFile(StringRef Filename,
192 OwningPtr<MemoryBuffer> &result,
194 // Ensure the path is null terminated.
195 SmallString<256> PathBuf(Filename.begin(), Filename.end());
196 return MemoryBuffer::getFile(PathBuf.c_str(), result, FileSize);
199 error_code MemoryBuffer::getFile(const char *Filename,
200 OwningPtr<MemoryBuffer> &result,
202 int OpenFlags = O_RDONLY;
204 OpenFlags |= O_BINARY; // Open input file in binary mode on win32.
206 int FD = ::open(Filename, OpenFlags);
208 return error_code(errno, posix_category());
211 return getOpenFile(FD, Filename, result, FileSize);
214 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
215 OwningPtr<MemoryBuffer> &result,
217 FileCloser FC(FD); // Close FD on return.
219 // If we don't know the file size, use fstat to find out. fstat on an open
220 // file descriptor is cheaper than stat on a random path.
221 if (FileSize == -1) {
222 struct stat FileInfo;
223 // TODO: This should use fstat64 when available.
224 if (fstat(FD, &FileInfo) == -1) {
225 return error_code(errno, posix_category());
227 FileSize = FileInfo.st_size;
231 // If the file is large, try to use mmap to read it in. We don't use mmap
232 // for small files, because this can severely fragment our address space. Also
233 // don't try to map files that are exactly a multiple of the system page size,
234 // as the file would not have the required null terminator.
236 // FIXME: Can we just mmap an extra page in the latter case?
237 if (FileSize >= 4096*4 &&
238 (FileSize & (sys::Process::GetPageSize()-1)) != 0) {
239 if (const char *Pages = sys::Path::MapInFilePages(FD, FileSize)) {
240 result.reset(GetNamedBuffer<MemoryBufferMMapFile>(
241 StringRef(Pages, FileSize), Filename));
246 MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(FileSize, Filename);
248 // Failed to create a buffer. The only way it can fail is if
249 // new(std::nothrow) returns 0.
250 return make_error_code(errc::not_enough_memory);
253 OwningPtr<MemoryBuffer> SB(Buf);
254 char *BufPtr = const_cast<char*>(SB->getBufferStart());
256 size_t BytesLeft = FileSize;
258 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
262 // Error while reading.
263 return error_code(errno, posix_category());
264 } else if (NumRead == 0) {
265 // We hit EOF early, truncate and terminate buffer.
266 Buf->BufferEnd = BufPtr;
271 BytesLeft -= NumRead;
279 //===----------------------------------------------------------------------===//
280 // MemoryBuffer::getSTDIN implementation.
281 //===----------------------------------------------------------------------===//
283 error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &result) {
284 // Read in all of the data from stdin, we cannot mmap stdin.
286 // FIXME: That isn't necessarily true, we should try to mmap stdin and
287 // fallback if it fails.
288 sys::Program::ChangeStdinToBinary();
290 const ssize_t ChunkSize = 4096*4;
291 SmallString<ChunkSize> Buffer;
293 // Read into Buffer until we hit EOF.
295 Buffer.reserve(Buffer.size() + ChunkSize);
296 ReadBytes = read(0, Buffer.end(), ChunkSize);
297 if (ReadBytes == -1) {
298 if (errno == EINTR) continue;
299 return error_code(errno, posix_category());
301 Buffer.set_size(Buffer.size() + ReadBytes);
302 } while (ReadBytes != 0);
304 result.reset(getMemBufferCopy(Buffer, "<stdin>"));