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/System/Errno.h"
18 #include "llvm/System/Path.h"
19 #include "llvm/System/Process.h"
20 #include "llvm/System/Program.h"
25 #include <sys/types.h>
27 #if !defined(_MSC_VER) && !defined(__MINGW32__)
36 //===----------------------------------------------------------------------===//
37 // MemoryBuffer implementation itself.
38 //===----------------------------------------------------------------------===//
40 MemoryBuffer::~MemoryBuffer() {
42 free((void*)BufferStart);
45 /// initCopyOf - Initialize this source buffer with a copy of the specified
46 /// memory range. We make the copy so that we can null terminate it
48 void MemoryBuffer::initCopyOf(const char *BufStart, const char *BufEnd) {
49 size_t Size = BufEnd-BufStart;
50 BufferStart = (char *)malloc(Size+1);
51 BufferEnd = BufferStart+Size;
52 memcpy(const_cast<char*>(BufferStart), BufStart, Size);
53 *const_cast<char*>(BufferEnd) = 0; // Null terminate buffer.
54 MustDeleteBuffer = true;
57 /// init - Initialize this MemoryBuffer as a reference to externally allocated
58 /// memory, memory that we know is already null terminated.
59 void MemoryBuffer::init(const char *BufStart, const char *BufEnd) {
60 assert(BufEnd[0] == 0 && "Buffer is not null terminated!");
61 BufferStart = BufStart;
63 MustDeleteBuffer = false;
66 //===----------------------------------------------------------------------===//
67 // MemoryBufferMem implementation.
68 //===----------------------------------------------------------------------===//
71 class MemoryBufferMem : public MemoryBuffer {
74 MemoryBufferMem(StringRef InputData, StringRef FID, bool Copy = false)
77 init(InputData.data(), InputData.data()+InputData.size());
79 initCopyOf(InputData.data(), InputData.data()+InputData.size());
82 virtual const char *getBufferIdentifier() const {
83 return FileID.c_str();
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 const char *BufferName) {
92 return new 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 const char *BufferName) {
100 return new MemoryBufferMem(InputData, BufferName, true);
103 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
104 /// that is completely initialized to zeros. Note that the caller should
105 /// initialize the memory allocated by this method. The memory is owned by
106 /// the MemoryBuffer object.
107 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
108 StringRef BufferName) {
109 char *Buf = (char *)malloc(Size+1);
112 MemoryBufferMem *SB = new MemoryBufferMem(StringRef(Buf, Size), BufferName);
113 // The memory for this buffer is owned by the MemoryBuffer.
114 SB->MustDeleteBuffer = true;
118 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
119 /// is completely initialized to zeros. Note that the caller should
120 /// initialize the memory allocated by this method. The memory is owned by
121 /// the MemoryBuffer object.
122 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size,
123 const char *BufferName) {
124 MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
126 memset(const_cast<char*>(SB->getBufferStart()), 0, Size+1);
131 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
132 /// if the Filename is "-". If an error occurs, this returns null and fills
133 /// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
134 /// returns an empty buffer.
135 MemoryBuffer *MemoryBuffer::getFileOrSTDIN(StringRef Filename,
138 struct stat *FileInfo) {
140 return getSTDIN(ErrStr);
141 return getFile(Filename, ErrStr, FileSize, FileInfo);
144 MemoryBuffer *MemoryBuffer::getFileOrSTDIN(const char *Filename,
147 struct stat *FileInfo) {
148 if (strcmp(Filename, "-") == 0)
149 return getSTDIN(ErrStr);
150 return getFile(Filename, ErrStr, FileSize, FileInfo);
153 //===----------------------------------------------------------------------===//
154 // MemoryBuffer::getFile implementation.
155 //===----------------------------------------------------------------------===//
158 /// MemoryBufferMMapFile - This represents a file that was mapped in with the
159 /// sys::Path::MapInFilePages method. When destroyed, it calls the
160 /// sys::Path::UnMapFilePages method.
161 class MemoryBufferMMapFile : public MemoryBuffer {
162 std::string Filename;
164 MemoryBufferMMapFile(StringRef filename, const char *Pages, uint64_t Size)
165 : Filename(filename) {
166 init(Pages, Pages+Size);
169 virtual const char *getBufferIdentifier() const {
170 return Filename.c_str();
173 ~MemoryBufferMMapFile() {
174 sys::Path::UnMapFilePages(getBufferStart(), getBufferSize());
178 /// FileCloser - RAII object to make sure an FD gets closed properly.
182 explicit FileCloser(int FD) : FD(FD) {}
183 ~FileCloser() { ::close(FD); }
187 MemoryBuffer *MemoryBuffer::getFile(StringRef Filename, std::string *ErrStr,
188 int64_t FileSize, struct stat *FileInfo) {
189 SmallString<256> PathBuf(Filename.begin(), Filename.end());
190 return MemoryBuffer::getFile(PathBuf.c_str(), ErrStr, FileSize, FileInfo);
193 MemoryBuffer *MemoryBuffer::getFile(const char *Filename, std::string *ErrStr,
194 int64_t FileSize, struct stat *FileInfo) {
195 int OpenFlags = O_RDONLY;
197 OpenFlags |= O_BINARY; // Open input file in binary mode on win32.
199 int FD = ::open(Filename, OpenFlags);
201 if (ErrStr) *ErrStr = sys::StrError();
204 FileCloser FC(FD); // Close FD on return.
206 // If we don't know the file size, use fstat to find out. fstat on an open
207 // file descriptor is cheaper than stat on a random path.
208 if (FileSize == -1 || FileInfo) {
209 struct stat MyFileInfo;
210 struct stat *FileInfoPtr = FileInfo? FileInfo : &MyFileInfo;
212 // TODO: This should use fstat64 when available.
213 if (fstat(FD, FileInfoPtr) == -1) {
214 if (ErrStr) *ErrStr = sys::StrError();
217 FileSize = FileInfoPtr->st_size;
221 // If the file is large, try to use mmap to read it in. We don't use mmap
222 // for small files, because this can severely fragment our address space. Also
223 // don't try to map files that are exactly a multiple of the system page size,
224 // as the file would not have the required null terminator.
226 // FIXME: Can we just mmap an extra page in the latter case?
227 if (FileSize >= 4096*4 &&
228 (FileSize & (sys::Process::GetPageSize()-1)) != 0) {
229 if (const char *Pages = sys::Path::MapInFilePages(FD, FileSize)) {
230 // Close the file descriptor, now that the whole file is in memory.
231 return new MemoryBufferMMapFile(Filename, Pages, FileSize);
235 MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(FileSize, Filename);
237 // Failed to create a buffer.
238 if (ErrStr) *ErrStr = "could not allocate buffer";
242 OwningPtr<MemoryBuffer> SB(Buf);
243 char *BufPtr = const_cast<char*>(SB->getBufferStart());
245 size_t BytesLeft = FileSize;
247 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
251 // Error while reading.
252 if (ErrStr) *ErrStr = sys::StrError();
254 } else if (NumRead == 0) {
255 // We hit EOF early, truncate and terminate buffer.
256 Buf->BufferEnd = BufPtr;
260 BytesLeft -= NumRead;
267 //===----------------------------------------------------------------------===//
268 // MemoryBuffer::getSTDIN implementation.
269 //===----------------------------------------------------------------------===//
272 class STDINBufferFile : public MemoryBuffer {
274 virtual const char *getBufferIdentifier() const {
280 MemoryBuffer *MemoryBuffer::getSTDIN(std::string *ErrStr) {
283 std::vector<char> FileData;
285 // Read in all of the data from stdin, we cannot mmap stdin.
287 // FIXME: That isn't necessarily true, we should try to mmap stdin and
288 // fallback if it fails.
289 sys::Program::ChangeStdinToBinary();
292 ReadBytes = fread(Buffer, sizeof(char), sizeof(Buffer), stdin);
293 FileData.insert(FileData.end(), Buffer, Buffer+ReadBytes);
294 } while (ReadBytes == sizeof(Buffer));
297 if (ErrStr) *ErrStr = "error reading from stdin";
301 FileData.push_back(0); // &FileData[Size] is invalid. So is &*FileData.end().
302 size_t Size = FileData.size();
303 MemoryBuffer *B = new STDINBufferFile();
304 B->initCopyOf(&FileData[0], &FileData[Size-1]);