blob: 4e4dabc5e73a6b07093e2e6bafe40ed1646e9036 [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>
29#include <sys/fcntl.h>
30#else
31#include <io.h>
32#endif
Chris Lattner333ffd42007-04-29 06:58:52 +000033using namespace llvm;
34
35//===----------------------------------------------------------------------===//
36// MemoryBuffer implementation itself.
37//===----------------------------------------------------------------------===//
38
39MemoryBuffer::~MemoryBuffer() {
40 if (MustDeleteBuffer)
41 delete [] BufferStart;
42}
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;
49 BufferStart = new char[Size+1];
50 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:
Chris Lattner3daae272007-10-09 21:46:38 +000073 MemoryBufferMem(const char *Start, const char *End, const char *FID,
74 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.
109MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(unsigned Size,
110 const char *BufferName) {
111 char *Buf = new char[Size+1];
112 Buf[Size] = 0;
113 MemoryBufferMem *SB = new MemoryBufferMem(Buf, Buf+Size, BufferName);
114 // The memory for this buffer is owned by the MemoryBuffer.
115 SB->MustDeleteBuffer = true;
116 return SB;
117}
118
119/// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
120/// is completely initialized to zeros. Note that the caller should
121/// initialize the memory allocated by this method. The memory is owned by
122/// the MemoryBuffer object.
123MemoryBuffer *MemoryBuffer::getNewMemBuffer(unsigned Size,
124 const char *BufferName) {
125 MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
126 memset(const_cast<char*>(SB->getBufferStart()), 0, Size+1);
127 return SB;
128}
129
130
Chris Lattner2b1f1062007-11-18 18:52:28 +0000131/// 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.
135MemoryBuffer *MemoryBuffer::getFileOrSTDIN(const char *FilenameStart,
136 unsigned FnSize,
137 std::string *ErrStr,
138 int64_t FileSize) {
139 if (FnSize != 1 || FilenameStart[0] != '-')
140 return getFile(FilenameStart, FnSize, ErrStr, FileSize);
141 MemoryBuffer *M = getSTDIN();
142 if (M) return M;
143
144 // If stdin was empty, M is null. Cons up an empty memory buffer now.
145 const char *EmptyStr = "";
146 return MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
147}
148
Chris Lattner333ffd42007-04-29 06:58:52 +0000149//===----------------------------------------------------------------------===//
Chris Lattner333ffd42007-04-29 06:58:52 +0000150// MemoryBuffer::getFile implementation.
151//===----------------------------------------------------------------------===//
152
Chris Lattner11da4cf2008-04-01 06:05:21 +0000153namespace {
154/// MemoryBufferMMapFile - This represents a file that was mapped in with the
155/// sys::Path::MapInFilePages method. When destroyed, it calls the
156/// sys::Path::UnMapFilePages method.
157class MemoryBufferMMapFile : public MemoryBuffer {
158 std::string Filename;
159public:
160 MemoryBufferMMapFile(const char *filename, const char *Pages, uint64_t Size)
161 : Filename(filename) {
162 init(Pages, Pages+Size);
163 }
164
165 virtual const char *getBufferIdentifier() const {
166 return Filename.c_str();
167 }
168
169 ~MemoryBufferMMapFile() {
170 sys::Path::UnMapFilePages(getBufferStart(), getBufferSize());
171 }
172};
173}
174
Chris Lattner333ffd42007-04-29 06:58:52 +0000175MemoryBuffer *MemoryBuffer::getFile(const char *FilenameStart, unsigned FnSize,
Chris Lattner11da4cf2008-04-01 06:05:21 +0000176 std::string *ErrStr, int64_t FileSize) {
177 // Null terminate the filename.
178 SmallString<1000> Filename(FilenameStart, FilenameStart+FnSize);
179 Filename.push_back(0);
Chris Lattner333ffd42007-04-29 06:58:52 +0000180
Chris Lattner11da4cf2008-04-01 06:05:21 +0000181 int OpenFlags = 0;
182#ifdef O_BINARY
183 Flags |= O_BINARY; // Open input file in binary mode on win32.
184#endif
185 int FD = ::open(&Filename[0], O_RDONLY|OpenFlags);
Chris Lattner333ffd42007-04-29 06:58:52 +0000186 if (FD == -1) {
Chris Lattner11da4cf2008-04-01 06:05:21 +0000187 if (ErrStr) *ErrStr = "could not open file";
Chris Lattner333ffd42007-04-29 06:58:52 +0000188 return 0;
189 }
190
Chris Lattner11da4cf2008-04-01 06:05:21 +0000191 // If we don't know the file size, use fstat to find out. fstat on an open
192 // file descriptor is cheaper than stat on a random path.
193 if (FileSize == -1) {
194 struct stat FileInfo;
195 // TODO: This should use fstat64 when available.
196 if (fstat(FD, &FileInfo) == -1) {
197 if (ErrStr) *ErrStr = "could not get file length";
198 ::close(FD);
199 return 0;
200 }
201 FileSize = FileInfo.st_size;
202 }
203
204
205 // If the file is large, try to use mmap to read it in. We don't use mmap
206 // for small files, because this can severely fragment our address space. Also
207 // don't try to map files that are exactly a multiple of the system page size,
208 // as the file would not have the required null terminator.
209 if (FileSize >= 4096*4 &&
210 (FileSize & (sys::Process::GetPageSize()-1)) != 0) {
211 if (const char *Pages = sys::Path::MapInFilePages(FD, FileSize)) {
212 // Close the file descriptor, now that the whole file is in memory.
213 ::close(FD);
214 return new MemoryBufferMMapFile(&Filename[0], Pages, FileSize);
215 }
216 }
217
218 OwningPtr<MemoryBuffer> SB;
219 SB.reset(MemoryBuffer::getNewUninitMemBuffer(FileSize, &Filename[0]));
220 char *BufPtr = const_cast<char*>(SB->getBufferStart());
221
Chris Lattner333ffd42007-04-29 06:58:52 +0000222 unsigned BytesLeft = FileSize;
223 while (BytesLeft) {
224 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
225 if (NumRead != -1) {
226 BytesLeft -= NumRead;
227 BufPtr += NumRead;
228 } else if (errno == EINTR) {
229 // try again
230 } else {
231 // error reading.
232 close(FD);
Chris Lattner11da4cf2008-04-01 06:05:21 +0000233 if (ErrStr) *ErrStr = "error reading file data";
Chris Lattner333ffd42007-04-29 06:58:52 +0000234 return 0;
235 }
236 }
237 close(FD);
238
Chris Lattner11da4cf2008-04-01 06:05:21 +0000239 return SB.take();
Chris Lattner333ffd42007-04-29 06:58:52 +0000240}
241
Chris Lattner333ffd42007-04-29 06:58:52 +0000242//===----------------------------------------------------------------------===//
243// MemoryBuffer::getSTDIN implementation.
244//===----------------------------------------------------------------------===//
245
246namespace {
247class STDINBufferFile : public MemoryBuffer {
248public:
249 virtual const char *getBufferIdentifier() const {
250 return "<stdin>";
251 }
252};
253}
254
255MemoryBuffer *MemoryBuffer::getSTDIN() {
256 char Buffer[4096*4];
257
258 std::vector<char> FileData;
259
260 // Read in all of the data from stdin, we cannot mmap stdin.
Jeff Cohen0fea8eb2007-05-07 15:21:46 +0000261 sys::Program::ChangeStdinToBinary();
Reid Spencer2372ccc2007-08-08 20:01:58 +0000262 while (size_t ReadBytes = fread(Buffer, sizeof(char), 4096*4, stdin))
Chris Lattner333ffd42007-04-29 06:58:52 +0000263 FileData.insert(FileData.end(), Buffer, Buffer+ReadBytes);
Reid Spencer2372ccc2007-08-08 20:01:58 +0000264
Nick Lewyckyea332942007-07-01 03:06:30 +0000265 FileData.push_back(0); // &FileData[Size] is invalid. So is &*FileData.end().
Chris Lattner333ffd42007-04-29 06:58:52 +0000266 size_t Size = FileData.size();
Reid Spencer2372ccc2007-08-08 20:01:58 +0000267 if (Size <= 1)
268 return 0;
Chris Lattner333ffd42007-04-29 06:58:52 +0000269 MemoryBuffer *B = new STDINBufferFile();
Nick Lewyckyea332942007-07-01 03:06:30 +0000270 B->initCopyOf(&FileData[0], &FileData[Size-1]);
Chris Lattner333ffd42007-04-29 06:58:52 +0000271 return B;
272}