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 //===----------------------------------------------------------------------===//
145 // MemoryBuffer::getFile implementation.
146 //===----------------------------------------------------------------------===//
149 /// MemoryBufferMMapFile - This represents a file that was mapped in with the
150 /// sys::Path::MapInFilePages method. When destroyed, it calls the
151 /// sys::Path::UnMapFilePages method.
152 class MemoryBufferMMapFile : public MemoryBuffer {
153 std::string Filename;
155 MemoryBufferMMapFile(StringRef filename, const char *Pages, uint64_t Size)
156 : Filename(filename) {
157 init(Pages, Pages+Size);
160 virtual const char *getBufferIdentifier() const {
161 return Filename.c_str();
164 ~MemoryBufferMMapFile() {
165 sys::Path::UnMapFilePages(getBufferStart(), getBufferSize());
169 /// FileCloser - RAII object to make sure an FD gets closed properly.
173 FileCloser(int FD) : FD(FD) {}
174 ~FileCloser() { ::close(FD); }
178 MemoryBuffer *MemoryBuffer::getFile(StringRef Filename, std::string *ErrStr,
179 int64_t FileSize, struct stat *FileInfo) {
182 OpenFlags |= O_BINARY; // Open input file in binary mode on win32.
184 SmallString<256> PathBuf(Filename.begin(), Filename.end());
185 int FD = ::open(PathBuf.c_str(), O_RDONLY|OpenFlags);
187 if (ErrStr) *ErrStr = sys::StrError();
190 FileCloser FC(FD); // Close FD on return.
192 // If we don't know the file size, use fstat to find out. fstat on an open
193 // file descriptor is cheaper than stat on a random path.
194 if (FileSize == -1 || FileInfo) {
195 struct stat MyFileInfo;
196 struct stat *FileInfoPtr = FileInfo? FileInfo : &MyFileInfo;
198 // TODO: This should use fstat64 when available.
199 if (fstat(FD, FileInfoPtr) == -1) {
200 if (ErrStr) *ErrStr = sys::StrError();
203 FileSize = FileInfoPtr->st_size;
207 // If the file is large, try to use mmap to read it in. We don't use mmap
208 // for small files, because this can severely fragment our address space. Also
209 // don't try to map files that are exactly a multiple of the system page size,
210 // as the file would not have the required null terminator.
212 // FIXME: Can we just mmap an extra page in the latter case?
213 if (FileSize >= 4096*4 &&
214 (FileSize & (sys::Process::GetPageSize()-1)) != 0) {
215 if (const char *Pages = sys::Path::MapInFilePages(FD, FileSize)) {
216 // Close the file descriptor, now that the whole file is in memory.
217 return new MemoryBufferMMapFile(Filename, Pages, FileSize);
221 MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(FileSize, Filename);
223 // Failed to create a buffer.
224 if (ErrStr) *ErrStr = "could not allocate buffer";
228 OwningPtr<MemoryBuffer> SB(Buf);
229 char *BufPtr = const_cast<char*>(SB->getBufferStart());
231 size_t BytesLeft = FileSize;
233 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
237 // Error while reading.
238 if (ErrStr) *ErrStr = sys::StrError();
240 } else if (NumRead == 0) {
241 // We hit EOF early, truncate and terminate buffer.
242 Buf->BufferEnd = BufPtr;
246 BytesLeft -= NumRead;
253 //===----------------------------------------------------------------------===//
254 // MemoryBuffer::getSTDIN implementation.
255 //===----------------------------------------------------------------------===//
258 class STDINBufferFile : public MemoryBuffer {
260 virtual const char *getBufferIdentifier() const {
266 MemoryBuffer *MemoryBuffer::getSTDIN(std::string *ErrStr) {
269 std::vector<char> FileData;
271 // Read in all of the data from stdin, we cannot mmap stdin.
273 // FIXME: That isn't necessarily true, we should try to mmap stdin and
274 // fallback if it fails.
275 sys::Program::ChangeStdinToBinary();
278 ReadBytes = fread(Buffer, sizeof(char), sizeof(Buffer), stdin);
279 FileData.insert(FileData.end(), Buffer, Buffer+ReadBytes);
280 } while (ReadBytes == sizeof(Buffer));
283 if (ErrStr) *ErrStr = "error reading from stdin";
287 FileData.push_back(0); // &FileData[Size] is invalid. So is &*FileData.end().
288 size_t Size = FileData.size();
289 MemoryBuffer *B = new STDINBufferFile();
290 B->initCopyOf(&FileData[0], &FileData[Size-1]);