blob: eb046d0eaf3869dcbd51a1c25d5ac575bd7d7806 [file] [log] [blame]
Chris Lattner333ffd42007-04-29 06:58:52 +00001//===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner333ffd42007-04-29 06:58:52 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the MemoryBuffer interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Support/MemoryBuffer.h"
Chris Lattner11da4cf2008-04-01 06:05:21 +000015#include "llvm/ADT/OwningPtr.h"
16#include "llvm/ADT/SmallString.h"
17#include "llvm/System/Path.h"
Chris Lattner333ffd42007-04-29 06:58:52 +000018#include "llvm/System/Process.h"
Jeff Cohen0fea8eb2007-05-07 15:21:46 +000019#include "llvm/System/Program.h"
Jeff Cohen9bc40602007-04-29 14:21:44 +000020#include <cassert>
Chris Lattner333ffd42007-04-29 06:58:52 +000021#include <cstdio>
22#include <cstring>
23#include <cerrno>
Chris Lattner11da4cf2008-04-01 06:05:21 +000024#include <sys/types.h>
25#include <sys/stat.h>
26#if !defined(_MSC_VER) && !defined(__MINGW32__)
27#include <unistd.h>
28#include <sys/uio.h>
Chris Lattner11da4cf2008-04-01 06:05:21 +000029#else
30#include <io.h>
31#endif
Gabor Greif88110802008-04-30 08:53:22 +000032#include <fcntl.h>
Chris Lattner333ffd42007-04-29 06:58:52 +000033using namespace llvm;
34
35//===----------------------------------------------------------------------===//
36// MemoryBuffer implementation itself.
37//===----------------------------------------------------------------------===//
38
39MemoryBuffer::~MemoryBuffer() {
40 if (MustDeleteBuffer)
Evan Chenge2b3fdd2009-02-13 08:24:55 +000041 free((void*)BufferStart);
Chris Lattner333ffd42007-04-29 06:58:52 +000042}
43
44/// initCopyOf - Initialize this source buffer with a copy of the specified
45/// memory range. We make the copy so that we can null terminate it
46/// successfully.
47void MemoryBuffer::initCopyOf(const char *BufStart, const char *BufEnd) {
48 size_t Size = BufEnd-BufStart;
Chris Lattner62dc8962009-12-23 23:03:24 +000049 BufferStart = (char *)malloc(Size+1);
Chris Lattner333ffd42007-04-29 06:58:52 +000050 BufferEnd = BufferStart+Size;
51 memcpy(const_cast<char*>(BufferStart), BufStart, Size);
52 *const_cast<char*>(BufferEnd) = 0; // Null terminate buffer.
Chris Lattnera24b04e2007-05-11 00:43:26 +000053 MustDeleteBuffer = true;
Chris Lattner333ffd42007-04-29 06:58:52 +000054}
55
56/// init - Initialize this MemoryBuffer as a reference to externally allocated
57/// memory, memory that we know is already null terminated.
58void MemoryBuffer::init(const char *BufStart, const char *BufEnd) {
59 assert(BufEnd[0] == 0 && "Buffer is not null terminated!");
60 BufferStart = BufStart;
61 BufferEnd = BufEnd;
62 MustDeleteBuffer = false;
63}
64
65//===----------------------------------------------------------------------===//
66// MemoryBufferMem implementation.
67//===----------------------------------------------------------------------===//
68
69namespace {
70class MemoryBufferMem : public MemoryBuffer {
71 std::string FileID;
72public:
Daniel Dunbard65267e2009-11-10 00:43:58 +000073 MemoryBufferMem(const char *Start, const char *End, StringRef FID,
Chris Lattner3daae272007-10-09 21:46:38 +000074 bool Copy = false)
Chris Lattner333ffd42007-04-29 06:58:52 +000075 : FileID(FID) {
Chris Lattner3daae272007-10-09 21:46:38 +000076 if (!Copy)
77 init(Start, End);
78 else
79 initCopyOf(Start, End);
Chris Lattner333ffd42007-04-29 06:58:52 +000080 }
81
82 virtual const char *getBufferIdentifier() const {
83 return FileID.c_str();
84 }
85};
86}
87
88/// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note
89/// that EndPtr[0] must be a null byte and be accessible!
90MemoryBuffer *MemoryBuffer::getMemBuffer(const char *StartPtr,
91 const char *EndPtr,
92 const char *BufferName) {
93 return new MemoryBufferMem(StartPtr, EndPtr, BufferName);
94}
95
Chris Lattner3daae272007-10-09 21:46:38 +000096/// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
97/// copying the contents and taking ownership of it. This has no requirements
98/// on EndPtr[0].
99MemoryBuffer *MemoryBuffer::getMemBufferCopy(const char *StartPtr,
100 const char *EndPtr,
101 const char *BufferName) {
102 return new MemoryBufferMem(StartPtr, EndPtr, BufferName, true);
103}
104
Chris Lattner333ffd42007-04-29 06:58:52 +0000105/// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
106/// that is completely initialized to zeros. Note that the caller should
107/// initialize the memory allocated by this method. The memory is owned by
108/// the MemoryBuffer object.
Evan Cheng34cd4a42008-05-05 18:30:58 +0000109MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
Daniel Dunbard65267e2009-11-10 00:43:58 +0000110 StringRef BufferName) {
Chris Lattner62dc8962009-12-23 23:03:24 +0000111 char *Buf = (char *)malloc(Size+1);
Evan Cheng726135a2009-02-13 07:54:34 +0000112 if (!Buf) return 0;
Chris Lattner333ffd42007-04-29 06:58:52 +0000113 Buf[Size] = 0;
114 MemoryBufferMem *SB = new MemoryBufferMem(Buf, Buf+Size, BufferName);
115 // The memory for this buffer is owned by the MemoryBuffer.
116 SB->MustDeleteBuffer = true;
117 return SB;
118}
119
120/// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
121/// is completely initialized to zeros. Note that the caller should
122/// initialize the memory allocated by this method. The memory is owned by
123/// the MemoryBuffer object.
Evan Cheng34cd4a42008-05-05 18:30:58 +0000124MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size,
Chris Lattner333ffd42007-04-29 06:58:52 +0000125 const char *BufferName) {
126 MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
Evan Cheng726135a2009-02-13 07:54:34 +0000127 if (!SB) return 0;
Chris Lattner333ffd42007-04-29 06:58:52 +0000128 memset(const_cast<char*>(SB->getBufferStart()), 0, Size+1);
129 return SB;
130}
131
132
Chris Lattner2b1f1062007-11-18 18:52:28 +0000133/// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
134/// if the Filename is "-". If an error occurs, this returns null and fills
135/// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
136/// returns an empty buffer.
Daniel Dunbard65267e2009-11-10 00:43:58 +0000137MemoryBuffer *MemoryBuffer::getFileOrSTDIN(StringRef Filename,
Chris Lattner2b1f1062007-11-18 18:52:28 +0000138 std::string *ErrStr,
139 int64_t FileSize) {
Daniel Dunbard65267e2009-11-10 00:43:58 +0000140 if (Filename == "-")
141 return getSTDIN();
142 return getFile(Filename, ErrStr, FileSize);
Chris Lattner2b1f1062007-11-18 18:52:28 +0000143}
144
Chris Lattner333ffd42007-04-29 06:58:52 +0000145//===----------------------------------------------------------------------===//
Chris Lattner333ffd42007-04-29 06:58:52 +0000146// MemoryBuffer::getFile implementation.
147//===----------------------------------------------------------------------===//
148
Chris Lattner11da4cf2008-04-01 06:05:21 +0000149namespace {
150/// MemoryBufferMMapFile - This represents a file that was mapped in with the
151/// sys::Path::MapInFilePages method. When destroyed, it calls the
152/// sys::Path::UnMapFilePages method.
153class MemoryBufferMMapFile : public MemoryBuffer {
154 std::string Filename;
155public:
Daniel Dunbard65267e2009-11-10 00:43:58 +0000156 MemoryBufferMMapFile(StringRef filename, const char *Pages, uint64_t Size)
Chris Lattner11da4cf2008-04-01 06:05:21 +0000157 : Filename(filename) {
158 init(Pages, Pages+Size);
159 }
160
161 virtual const char *getBufferIdentifier() const {
162 return Filename.c_str();
163 }
164
165 ~MemoryBufferMMapFile() {
166 sys::Path::UnMapFilePages(getBufferStart(), getBufferSize());
167 }
168};
169}
170
Daniel Dunbard65267e2009-11-10 00:43:58 +0000171MemoryBuffer *MemoryBuffer::getFile(StringRef Filename, std::string *ErrStr,
Chris Lattner038112a2008-04-01 18:04:03 +0000172 int64_t FileSize) {
Chris Lattner11da4cf2008-04-01 06:05:21 +0000173 int OpenFlags = 0;
174#ifdef O_BINARY
Bill Wendlinga4420062008-04-01 22:09:20 +0000175 OpenFlags |= O_BINARY; // Open input file in binary mode on win32.
Chris Lattner11da4cf2008-04-01 06:05:21 +0000176#endif
Benjamin Krameraabc26c2010-02-26 20:28:29 +0000177 SmallString<256> PathBuf(Filename.begin(), Filename.end());
178 int FD = ::open(PathBuf.c_str(), O_RDONLY|OpenFlags);
Chris Lattner333ffd42007-04-29 06:58:52 +0000179 if (FD == -1) {
Chris Lattner6e1f16d2009-12-01 22:51:41 +0000180 if (ErrStr) *ErrStr = strerror(errno);
Chris Lattner333ffd42007-04-29 06:58:52 +0000181 return 0;
182 }
183
Chris Lattner11da4cf2008-04-01 06:05:21 +0000184 // If we don't know the file size, use fstat to find out. fstat on an open
185 // file descriptor is cheaper than stat on a random path.
186 if (FileSize == -1) {
187 struct stat FileInfo;
188 // TODO: This should use fstat64 when available.
189 if (fstat(FD, &FileInfo) == -1) {
Chris Lattner6e1f16d2009-12-01 22:51:41 +0000190 if (ErrStr) *ErrStr = strerror(errno);
Chris Lattner11da4cf2008-04-01 06:05:21 +0000191 ::close(FD);
192 return 0;
193 }
194 FileSize = FileInfo.st_size;
195 }
196
197
198 // If the file is large, try to use mmap to read it in. We don't use mmap
199 // for small files, because this can severely fragment our address space. Also
200 // don't try to map files that are exactly a multiple of the system page size,
201 // as the file would not have the required null terminator.
Daniel Dunbard65267e2009-11-10 00:43:58 +0000202 //
203 // FIXME: Can we just mmap an extra page in the latter case?
Chris Lattner11da4cf2008-04-01 06:05:21 +0000204 if (FileSize >= 4096*4 &&
205 (FileSize & (sys::Process::GetPageSize()-1)) != 0) {
206 if (const char *Pages = sys::Path::MapInFilePages(FD, FileSize)) {
207 // Close the file descriptor, now that the whole file is in memory.
208 ::close(FD);
Chris Lattner038112a2008-04-01 18:04:03 +0000209 return new MemoryBufferMMapFile(Filename, Pages, FileSize);
Chris Lattner11da4cf2008-04-01 06:05:21 +0000210 }
211 }
Evan Cheng726135a2009-02-13 07:54:34 +0000212
213 MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(FileSize, Filename);
214 if (!Buf) {
215 // Failed to create a buffer.
216 if (ErrStr) *ErrStr = "could not allocate buffer";
217 ::close(FD);
218 return 0;
219 }
220
221 OwningPtr<MemoryBuffer> SB(Buf);
Chris Lattner11da4cf2008-04-01 06:05:21 +0000222 char *BufPtr = const_cast<char*>(SB->getBufferStart());
223
Evan Cheng34cd4a42008-05-05 18:30:58 +0000224 size_t BytesLeft = FileSize;
Chris Lattner333ffd42007-04-29 06:58:52 +0000225 while (BytesLeft) {
226 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
Duncan Sands954cb432009-11-03 19:10:22 +0000227 if (NumRead > 0) {
Chris Lattner333ffd42007-04-29 06:58:52 +0000228 BytesLeft -= NumRead;
229 BufPtr += NumRead;
Duncan Sands7127b132009-11-04 20:50:23 +0000230 } else if (NumRead == -1 && errno == EINTR) {
Chris Lattner333ffd42007-04-29 06:58:52 +0000231 // try again
232 } else {
233 // error reading.
Chris Lattner6e1f16d2009-12-01 22:51:41 +0000234 if (ErrStr) *ErrStr = strerror(errno);
Chris Lattner333ffd42007-04-29 06:58:52 +0000235 close(FD);
Chris Lattner333ffd42007-04-29 06:58:52 +0000236 return 0;
237 }
238 }
239 close(FD);
240
Chris Lattner11da4cf2008-04-01 06:05:21 +0000241 return SB.take();
Chris Lattner333ffd42007-04-29 06:58:52 +0000242}
243
Chris Lattner333ffd42007-04-29 06:58:52 +0000244//===----------------------------------------------------------------------===//
245// MemoryBuffer::getSTDIN implementation.
246//===----------------------------------------------------------------------===//
247
248namespace {
249class STDINBufferFile : public MemoryBuffer {
250public:
251 virtual const char *getBufferIdentifier() const {
252 return "<stdin>";
253 }
254};
255}
256
257MemoryBuffer *MemoryBuffer::getSTDIN() {
258 char Buffer[4096*4];
Eli Friedman96cd7af2009-05-18 08:44:04 +0000259
Chris Lattner333ffd42007-04-29 06:58:52 +0000260 std::vector<char> FileData;
Eli Friedman96cd7af2009-05-18 08:44:04 +0000261
Chris Lattner333ffd42007-04-29 06:58:52 +0000262 // Read in all of the data from stdin, we cannot mmap stdin.
Daniel Dunbard65267e2009-11-10 00:43:58 +0000263 //
264 // FIXME: That isn't necessarily true, we should try to mmap stdin and
265 // fallback if it fails.
Jeff Cohen0fea8eb2007-05-07 15:21:46 +0000266 sys::Program::ChangeStdinToBinary();
Eli Friedman96cd7af2009-05-18 08:44:04 +0000267 size_t ReadBytes;
268 do {
269 ReadBytes = fread(Buffer, sizeof(char), sizeof(Buffer), stdin);
Chris Lattner333ffd42007-04-29 06:58:52 +0000270 FileData.insert(FileData.end(), Buffer, Buffer+ReadBytes);
Eli Friedman96cd7af2009-05-18 08:44:04 +0000271 } while (ReadBytes == sizeof(Buffer));
Reid Spencer2372ccc2007-08-08 20:01:58 +0000272
Nick Lewyckyea332942007-07-01 03:06:30 +0000273 FileData.push_back(0); // &FileData[Size] is invalid. So is &*FileData.end().
Chris Lattner333ffd42007-04-29 06:58:52 +0000274 size_t Size = FileData.size();
275 MemoryBuffer *B = new STDINBufferFile();
Nick Lewyckyea332942007-07-01 03:06:30 +0000276 B->initCopyOf(&FileData[0], &FileData[Size-1]);
Chris Lattner333ffd42007-04-29 06:58:52 +0000277 return B;
278}