blob: 9c84b30f91d980e66c71485b0dbc8ce59b823f0a [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"
Benjamin Kramer6a9cd412010-04-01 14:35:22 +000017#include "llvm/ADT/StringExtras.h"
18#include "llvm/System/Errno.h"
Chris Lattner11da4cf2008-04-01 06:05:21 +000019#include "llvm/System/Path.h"
Chris Lattner333ffd42007-04-29 06:58:52 +000020#include "llvm/System/Process.h"
Jeff Cohen0fea8eb2007-05-07 15:21:46 +000021#include "llvm/System/Program.h"
Jeff Cohen9bc40602007-04-29 14:21:44 +000022#include <cassert>
Chris Lattner333ffd42007-04-29 06:58:52 +000023#include <cstdio>
24#include <cstring>
25#include <cerrno>
Chris Lattner11da4cf2008-04-01 06:05:21 +000026#include <sys/types.h>
27#include <sys/stat.h>
28#if !defined(_MSC_VER) && !defined(__MINGW32__)
29#include <unistd.h>
30#include <sys/uio.h>
Chris Lattner11da4cf2008-04-01 06:05:21 +000031#else
32#include <io.h>
33#endif
Gabor Greif88110802008-04-30 08:53:22 +000034#include <fcntl.h>
Chris Lattner333ffd42007-04-29 06:58:52 +000035using namespace llvm;
36
37//===----------------------------------------------------------------------===//
38// MemoryBuffer implementation itself.
39//===----------------------------------------------------------------------===//
40
41MemoryBuffer::~MemoryBuffer() {
42 if (MustDeleteBuffer)
Evan Chenge2b3fdd2009-02-13 08:24:55 +000043 free((void*)BufferStart);
Chris Lattner333ffd42007-04-29 06:58:52 +000044}
45
46/// initCopyOf - Initialize this source buffer with a copy of the specified
47/// memory range. We make the copy so that we can null terminate it
48/// successfully.
49void MemoryBuffer::initCopyOf(const char *BufStart, const char *BufEnd) {
50 size_t Size = BufEnd-BufStart;
Chris Lattner62dc8962009-12-23 23:03:24 +000051 BufferStart = (char *)malloc(Size+1);
Chris Lattner333ffd42007-04-29 06:58:52 +000052 BufferEnd = BufferStart+Size;
53 memcpy(const_cast<char*>(BufferStart), BufStart, Size);
54 *const_cast<char*>(BufferEnd) = 0; // Null terminate buffer.
Chris Lattnera24b04e2007-05-11 00:43:26 +000055 MustDeleteBuffer = true;
Chris Lattner333ffd42007-04-29 06:58:52 +000056}
57
58/// init - Initialize this MemoryBuffer as a reference to externally allocated
59/// memory, memory that we know is already null terminated.
60void MemoryBuffer::init(const char *BufStart, const char *BufEnd) {
61 assert(BufEnd[0] == 0 && "Buffer is not null terminated!");
62 BufferStart = BufStart;
63 BufferEnd = BufEnd;
64 MustDeleteBuffer = false;
65}
66
67//===----------------------------------------------------------------------===//
68// MemoryBufferMem implementation.
69//===----------------------------------------------------------------------===//
70
71namespace {
72class MemoryBufferMem : public MemoryBuffer {
73 std::string FileID;
74public:
Daniel Dunbard65267e2009-11-10 00:43:58 +000075 MemoryBufferMem(const char *Start, const char *End, StringRef FID,
Chris Lattner3daae272007-10-09 21:46:38 +000076 bool Copy = false)
Chris Lattner333ffd42007-04-29 06:58:52 +000077 : FileID(FID) {
Chris Lattner3daae272007-10-09 21:46:38 +000078 if (!Copy)
79 init(Start, End);
80 else
81 initCopyOf(Start, End);
Chris Lattner333ffd42007-04-29 06:58:52 +000082 }
83
84 virtual const char *getBufferIdentifier() const {
85 return FileID.c_str();
86 }
87};
88}
89
90/// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note
91/// that EndPtr[0] must be a null byte and be accessible!
92MemoryBuffer *MemoryBuffer::getMemBuffer(const char *StartPtr,
93 const char *EndPtr,
94 const char *BufferName) {
95 return new MemoryBufferMem(StartPtr, EndPtr, BufferName);
96}
97
Chris Lattner3daae272007-10-09 21:46:38 +000098/// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
99/// copying the contents and taking ownership of it. This has no requirements
100/// on EndPtr[0].
101MemoryBuffer *MemoryBuffer::getMemBufferCopy(const char *StartPtr,
102 const char *EndPtr,
103 const char *BufferName) {
104 return new MemoryBufferMem(StartPtr, EndPtr, BufferName, true);
105}
106
Chris Lattner333ffd42007-04-29 06:58:52 +0000107/// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
108/// that is completely initialized to zeros. Note that the caller should
109/// initialize the memory allocated by this method. The memory is owned by
110/// the MemoryBuffer object.
Evan Cheng34cd4a42008-05-05 18:30:58 +0000111MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
Daniel Dunbard65267e2009-11-10 00:43:58 +0000112 StringRef BufferName) {
Chris Lattner62dc8962009-12-23 23:03:24 +0000113 char *Buf = (char *)malloc(Size+1);
Evan Cheng726135a2009-02-13 07:54:34 +0000114 if (!Buf) return 0;
Chris Lattner333ffd42007-04-29 06:58:52 +0000115 Buf[Size] = 0;
116 MemoryBufferMem *SB = new MemoryBufferMem(Buf, Buf+Size, BufferName);
117 // The memory for this buffer is owned by the MemoryBuffer.
118 SB->MustDeleteBuffer = true;
119 return SB;
120}
121
122/// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
123/// is completely initialized to zeros. Note that the caller should
124/// initialize the memory allocated by this method. The memory is owned by
125/// the MemoryBuffer object.
Evan Cheng34cd4a42008-05-05 18:30:58 +0000126MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size,
Chris Lattner333ffd42007-04-29 06:58:52 +0000127 const char *BufferName) {
128 MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
Evan Cheng726135a2009-02-13 07:54:34 +0000129 if (!SB) return 0;
Chris Lattner333ffd42007-04-29 06:58:52 +0000130 memset(const_cast<char*>(SB->getBufferStart()), 0, Size+1);
131 return SB;
132}
133
134
Chris Lattner2b1f1062007-11-18 18:52:28 +0000135/// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
136/// if the Filename is "-". If an error occurs, this returns null and fills
137/// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
138/// returns an empty buffer.
Daniel Dunbard65267e2009-11-10 00:43:58 +0000139MemoryBuffer *MemoryBuffer::getFileOrSTDIN(StringRef Filename,
Chris Lattner2b1f1062007-11-18 18:52:28 +0000140 std::string *ErrStr,
Douglas Gregor1bb30b62010-03-15 20:32:14 +0000141 int64_t FileSize,
142 struct stat *FileInfo) {
Daniel Dunbard65267e2009-11-10 00:43:58 +0000143 if (Filename == "-")
144 return getSTDIN();
Douglas Gregor1bb30b62010-03-15 20:32:14 +0000145 return getFile(Filename, ErrStr, FileSize, FileInfo);
Chris Lattner2b1f1062007-11-18 18:52:28 +0000146}
147
Chris Lattner333ffd42007-04-29 06:58:52 +0000148//===----------------------------------------------------------------------===//
Chris Lattner333ffd42007-04-29 06:58:52 +0000149// MemoryBuffer::getFile implementation.
150//===----------------------------------------------------------------------===//
151
Chris Lattner11da4cf2008-04-01 06:05:21 +0000152namespace {
153/// MemoryBufferMMapFile - This represents a file that was mapped in with the
154/// sys::Path::MapInFilePages method. When destroyed, it calls the
155/// sys::Path::UnMapFilePages method.
156class MemoryBufferMMapFile : public MemoryBuffer {
157 std::string Filename;
158public:
Daniel Dunbard65267e2009-11-10 00:43:58 +0000159 MemoryBufferMMapFile(StringRef filename, const char *Pages, uint64_t Size)
Chris Lattner11da4cf2008-04-01 06:05:21 +0000160 : Filename(filename) {
161 init(Pages, Pages+Size);
162 }
163
164 virtual const char *getBufferIdentifier() const {
165 return Filename.c_str();
166 }
167
168 ~MemoryBufferMMapFile() {
169 sys::Path::UnMapFilePages(getBufferStart(), getBufferSize());
170 }
171};
Benjamin Kramer6a9cd412010-04-01 14:35:22 +0000172
173/// FileCloser - RAII object to make sure an FD gets closed properly.
174class FileCloser {
175 int FD;
176public:
177 FileCloser(int FD) : FD(FD) {}
178 ~FileCloser() { ::close(FD); }
179};
Chris Lattner11da4cf2008-04-01 06:05:21 +0000180}
181
Daniel Dunbard65267e2009-11-10 00:43:58 +0000182MemoryBuffer *MemoryBuffer::getFile(StringRef Filename, std::string *ErrStr,
Douglas Gregor1bb30b62010-03-15 20:32:14 +0000183 int64_t FileSize, struct stat *FileInfo) {
Chris Lattner11da4cf2008-04-01 06:05:21 +0000184 int OpenFlags = 0;
185#ifdef O_BINARY
Bill Wendlinga4420062008-04-01 22:09:20 +0000186 OpenFlags |= O_BINARY; // Open input file in binary mode on win32.
Chris Lattner11da4cf2008-04-01 06:05:21 +0000187#endif
Benjamin Krameraabc26c2010-02-26 20:28:29 +0000188 SmallString<256> PathBuf(Filename.begin(), Filename.end());
189 int FD = ::open(PathBuf.c_str(), O_RDONLY|OpenFlags);
Chris Lattner333ffd42007-04-29 06:58:52 +0000190 if (FD == -1) {
Benjamin Kramer6a9cd412010-04-01 14:35:22 +0000191 if (ErrStr) *ErrStr = sys::StrError();
Chris Lattner333ffd42007-04-29 06:58:52 +0000192 return 0;
193 }
Benjamin Kramer6a9cd412010-04-01 14:35:22 +0000194 FileCloser FC(FD); // Close FD on return.
Chris Lattner333ffd42007-04-29 06:58:52 +0000195
Chris Lattner11da4cf2008-04-01 06:05:21 +0000196 // If we don't know the file size, use fstat to find out. fstat on an open
197 // file descriptor is cheaper than stat on a random path.
Douglas Gregor1bb30b62010-03-15 20:32:14 +0000198 if (FileSize == -1 || FileInfo) {
199 struct stat MyFileInfo;
200 struct stat *FileInfoPtr = FileInfo? FileInfo : &MyFileInfo;
201
Chris Lattner11da4cf2008-04-01 06:05:21 +0000202 // TODO: This should use fstat64 when available.
Douglas Gregor1bb30b62010-03-15 20:32:14 +0000203 if (fstat(FD, FileInfoPtr) == -1) {
Benjamin Kramer6a9cd412010-04-01 14:35:22 +0000204 if (ErrStr) *ErrStr = sys::StrError();
Chris Lattner11da4cf2008-04-01 06:05:21 +0000205 return 0;
206 }
Douglas Gregor1bb30b62010-03-15 20:32:14 +0000207 FileSize = FileInfoPtr->st_size;
Chris Lattner11da4cf2008-04-01 06:05:21 +0000208 }
209
210
211 // If the file is large, try to use mmap to read it in. We don't use mmap
212 // for small files, because this can severely fragment our address space. Also
213 // don't try to map files that are exactly a multiple of the system page size,
214 // as the file would not have the required null terminator.
Daniel Dunbard65267e2009-11-10 00:43:58 +0000215 //
216 // FIXME: Can we just mmap an extra page in the latter case?
Chris Lattner11da4cf2008-04-01 06:05:21 +0000217 if (FileSize >= 4096*4 &&
218 (FileSize & (sys::Process::GetPageSize()-1)) != 0) {
219 if (const char *Pages = sys::Path::MapInFilePages(FD, FileSize)) {
220 // Close the file descriptor, now that the whole file is in memory.
Chris Lattner038112a2008-04-01 18:04:03 +0000221 return new MemoryBufferMMapFile(Filename, Pages, FileSize);
Chris Lattner11da4cf2008-04-01 06:05:21 +0000222 }
223 }
Evan Cheng726135a2009-02-13 07:54:34 +0000224
225 MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(FileSize, Filename);
226 if (!Buf) {
227 // Failed to create a buffer.
228 if (ErrStr) *ErrStr = "could not allocate buffer";
Evan Cheng726135a2009-02-13 07:54:34 +0000229 return 0;
230 }
231
232 OwningPtr<MemoryBuffer> SB(Buf);
Chris Lattner11da4cf2008-04-01 06:05:21 +0000233 char *BufPtr = const_cast<char*>(SB->getBufferStart());
Benjamin Kramer6a9cd412010-04-01 14:35:22 +0000234
Evan Cheng34cd4a42008-05-05 18:30:58 +0000235 size_t BytesLeft = FileSize;
Chris Lattner333ffd42007-04-29 06:58:52 +0000236 while (BytesLeft) {
237 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
Benjamin Kramer6a9cd412010-04-01 14:35:22 +0000238 if (NumRead == -1) {
239 if (errno == EINTR)
240 continue;
241 // Error while reading.
242 if (ErrStr) *ErrStr = sys::StrError();
Chris Lattner333ffd42007-04-29 06:58:52 +0000243 return 0;
Benjamin Kramer6a9cd412010-04-01 14:35:22 +0000244 } else if (NumRead == 0) {
245 Buf->BufferEnd = BufPtr;
246 *BufPtr = 0; // Null terminate buffer.
247 return SB.take();
Chris Lattner333ffd42007-04-29 06:58:52 +0000248 }
Benjamin Kramer6a9cd412010-04-01 14:35:22 +0000249 BytesLeft -= NumRead;
250 BufPtr += NumRead;
Chris Lattner333ffd42007-04-29 06:58:52 +0000251 }
Benjamin Kramer6a9cd412010-04-01 14:35:22 +0000252
Chris Lattner11da4cf2008-04-01 06:05:21 +0000253 return SB.take();
Chris Lattner333ffd42007-04-29 06:58:52 +0000254}
255
Chris Lattner333ffd42007-04-29 06:58:52 +0000256//===----------------------------------------------------------------------===//
257// MemoryBuffer::getSTDIN implementation.
258//===----------------------------------------------------------------------===//
259
260namespace {
261class STDINBufferFile : public MemoryBuffer {
262public:
263 virtual const char *getBufferIdentifier() const {
264 return "<stdin>";
265 }
266};
267}
268
269MemoryBuffer *MemoryBuffer::getSTDIN() {
270 char Buffer[4096*4];
Eli Friedman96cd7af2009-05-18 08:44:04 +0000271
Chris Lattner333ffd42007-04-29 06:58:52 +0000272 std::vector<char> FileData;
Eli Friedman96cd7af2009-05-18 08:44:04 +0000273
Chris Lattner333ffd42007-04-29 06:58:52 +0000274 // Read in all of the data from stdin, we cannot mmap stdin.
Daniel Dunbard65267e2009-11-10 00:43:58 +0000275 //
276 // FIXME: That isn't necessarily true, we should try to mmap stdin and
277 // fallback if it fails.
Jeff Cohen0fea8eb2007-05-07 15:21:46 +0000278 sys::Program::ChangeStdinToBinary();
Eli Friedman96cd7af2009-05-18 08:44:04 +0000279 size_t ReadBytes;
280 do {
281 ReadBytes = fread(Buffer, sizeof(char), sizeof(Buffer), stdin);
Chris Lattner333ffd42007-04-29 06:58:52 +0000282 FileData.insert(FileData.end(), Buffer, Buffer+ReadBytes);
Eli Friedman96cd7af2009-05-18 08:44:04 +0000283 } while (ReadBytes == sizeof(Buffer));
Reid Spencer2372ccc2007-08-08 20:01:58 +0000284
Nick Lewyckyea332942007-07-01 03:06:30 +0000285 FileData.push_back(0); // &FileData[Size] is invalid. So is &*FileData.end().
Chris Lattner333ffd42007-04-29 06:58:52 +0000286 size_t Size = FileData.size();
287 MemoryBuffer *B = new STDINBufferFile();
Nick Lewyckyea332942007-07-01 03:06:30 +0000288 B->initCopyOf(&FileData[0], &FileData[Size-1]);
Chris Lattner333ffd42007-04-29 06:58:52 +0000289 return B;
290}