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/Support/MathExtras.h"
18 #include "llvm/Support/Errno.h"
19 #include "llvm/Support/Path.h"
20 #include "llvm/Support/Process.h"
21 #include "llvm/Support/Program.h"
22 #include "llvm/Support/system_error.h"
28 #include <sys/types.h>
30 #if !defined(_MSC_VER) && !defined(__MINGW32__)
39 namespace { const llvm::error_code success
; }
41 //===----------------------------------------------------------------------===//
42 // MemoryBuffer implementation itself.
43 //===----------------------------------------------------------------------===//
45 MemoryBuffer::~MemoryBuffer() { }
47 /// init - Initialize this MemoryBuffer as a reference to externally allocated
48 /// memory, memory that we know is already null terminated.
49 void MemoryBuffer::init(const char *BufStart
, const char *BufEnd
,
50 bool RequiresNullTerminator
) {
51 assert((!RequiresNullTerminator
|| BufEnd
[0] == 0) &&
52 "Buffer is not null terminated!");
53 BufferStart
= BufStart
;
57 //===----------------------------------------------------------------------===//
58 // MemoryBufferMem implementation.
59 //===----------------------------------------------------------------------===//
61 /// CopyStringRef - Copies contents of a StringRef into a block of memory and
62 /// null-terminates it.
63 static void CopyStringRef(char *Memory
, StringRef Data
) {
64 memcpy(Memory
, Data
.data(), Data
.size());
65 Memory
[Data
.size()] = 0; // Null terminate string.
68 /// GetNamedBuffer - Allocates a new MemoryBuffer with Name copied after it.
70 static T
* GetNamedBuffer(StringRef Buffer
, StringRef Name
,
71 bool RequiresNullTerminator
) {
72 char *Mem
= static_cast<char*>(operator new(sizeof(T
) + Name
.size() + 1));
73 CopyStringRef(Mem
+ sizeof(T
), Name
);
74 return new (Mem
) T(Buffer
, RequiresNullTerminator
);
78 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
79 class MemoryBufferMem
: public MemoryBuffer
{
81 MemoryBufferMem(StringRef InputData
, bool RequiresNullTerminator
) {
82 init(InputData
.begin(), InputData
.end(), RequiresNullTerminator
);
85 virtual const char *getBufferIdentifier() const {
86 // The name is stored after the class itself.
87 return reinterpret_cast<const char*>(this + 1);
92 /// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note
93 /// that EndPtr[0] must be a null byte and be accessible!
94 MemoryBuffer
*MemoryBuffer::getMemBuffer(StringRef InputData
,
96 bool RequiresNullTerminator
) {
97 return GetNamedBuffer
<MemoryBufferMem
>(InputData
, BufferName
,
98 RequiresNullTerminator
);
101 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
102 /// copying the contents and taking ownership of it. This has no requirements
104 MemoryBuffer
*MemoryBuffer::getMemBufferCopy(StringRef InputData
,
105 StringRef BufferName
) {
106 MemoryBuffer
*Buf
= getNewUninitMemBuffer(InputData
.size(), BufferName
);
108 memcpy(const_cast<char*>(Buf
->getBufferStart()), InputData
.data(),
113 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
114 /// that is not initialized. Note that the caller should initialize the
115 /// memory allocated by this method. The memory is owned by the MemoryBuffer
117 MemoryBuffer
*MemoryBuffer::getNewUninitMemBuffer(size_t Size
,
118 StringRef BufferName
) {
119 // Allocate space for the MemoryBuffer, the data and the name. It is important
120 // that MemoryBuffer and data are aligned so PointerIntPair works with them.
121 size_t AlignedStringLen
=
122 RoundUpToAlignment(sizeof(MemoryBufferMem
) + BufferName
.size() + 1,
123 sizeof(void*)); // TODO: Is sizeof(void*) enough?
124 size_t RealLen
= AlignedStringLen
+ Size
+ 1;
125 char *Mem
= static_cast<char*>(operator new(RealLen
, std::nothrow
));
128 // The name is stored after the class itself.
129 CopyStringRef(Mem
+ sizeof(MemoryBufferMem
), BufferName
);
131 // The buffer begins after the name and must be aligned.
132 char *Buf
= Mem
+ AlignedStringLen
;
133 Buf
[Size
] = 0; // Null terminate buffer.
135 return new (Mem
) MemoryBufferMem(StringRef(Buf
, Size
), true);
138 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
139 /// is completely initialized to zeros. Note that the caller should
140 /// initialize the memory allocated by this method. The memory is owned by
141 /// the MemoryBuffer object.
142 MemoryBuffer
*MemoryBuffer::getNewMemBuffer(size_t Size
, StringRef BufferName
) {
143 MemoryBuffer
*SB
= getNewUninitMemBuffer(Size
, BufferName
);
145 memset(const_cast<char*>(SB
->getBufferStart()), 0, Size
);
150 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
151 /// if the Filename is "-". If an error occurs, this returns null and fills
152 /// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
153 /// returns an empty buffer.
154 error_code
MemoryBuffer::getFileOrSTDIN(StringRef Filename
,
155 OwningPtr
<MemoryBuffer
> &result
,
158 return getSTDIN(result
);
159 return getFile(Filename
, result
, FileSize
);
162 error_code
MemoryBuffer::getFileOrSTDIN(const char *Filename
,
163 OwningPtr
<MemoryBuffer
> &result
,
165 if (strcmp(Filename
, "-") == 0)
166 return getSTDIN(result
);
167 return getFile(Filename
, result
, FileSize
);
170 //===----------------------------------------------------------------------===//
171 // MemoryBuffer::getFile implementation.
172 //===----------------------------------------------------------------------===//
175 /// MemoryBufferMMapFile - This represents a file that was mapped in with the
176 /// sys::Path::MapInFilePages method. When destroyed, it calls the
177 /// sys::Path::UnMapFilePages method.
178 class MemoryBufferMMapFile
: public MemoryBufferMem
{
180 MemoryBufferMMapFile(StringRef Buffer
, bool RequiresNullTerminator
)
181 : MemoryBufferMem(Buffer
, RequiresNullTerminator
) { }
183 ~MemoryBufferMMapFile() {
184 static int PageSize
= sys::Process::GetPageSize();
186 uintptr_t Start
= reinterpret_cast<uintptr_t>(getBufferStart());
187 size_t Size
= getBufferSize();
188 uintptr_t RealStart
= Start
& ~(PageSize
- 1);
189 size_t RealSize
= Size
+ (Start
- RealStart
);
191 sys::Path::UnMapFilePages(reinterpret_cast<const char*>(RealStart
),
197 error_code
MemoryBuffer::getFile(StringRef Filename
,
198 OwningPtr
<MemoryBuffer
> &result
,
200 bool RequiresNullTerminator
) {
201 // Ensure the path is null terminated.
202 SmallString
<256> PathBuf(Filename
.begin(), Filename
.end());
203 return MemoryBuffer::getFile(PathBuf
.c_str(), result
, FileSize
,
204 RequiresNullTerminator
);
207 error_code
MemoryBuffer::getFile(const char *Filename
,
208 OwningPtr
<MemoryBuffer
> &result
,
210 bool RequiresNullTerminator
) {
211 int OpenFlags
= O_RDONLY
;
213 OpenFlags
|= O_BINARY
; // Open input file in binary mode on win32.
215 int FD
= ::open(Filename
, OpenFlags
);
217 return error_code(errno
, posix_category());
219 error_code ret
= getOpenFile(FD
, Filename
, result
, FileSize
, FileSize
,
220 0, RequiresNullTerminator
);
225 static bool shouldUseMmap(int FD
,
229 bool RequiresNullTerminator
,
231 // We don't use mmap for small files because this can severely fragment our
233 if (MapSize
< 4096*4)
236 if (!RequiresNullTerminator
)
240 // If we don't know the file size, use fstat to find out. fstat on an open
241 // file descriptor is cheaper than stat on a random path.
242 // FIXME: this chunk of code is duplicated, but it avoids a fstat when
243 // RequiresNullTerminator = false and MapSize != -1.
244 if (FileSize
== size_t(-1)) {
245 struct stat FileInfo
;
246 // TODO: This should use fstat64 when available.
247 if (fstat(FD
, &FileInfo
) == -1) {
248 return error_code(errno
, posix_category());
250 FileSize
= FileInfo
.st_size
;
253 // If we need a null terminator and the end of the map is inside the file,
254 // we cannot use mmap.
255 size_t End
= Offset
+ MapSize
;
256 assert(End
<= FileSize
);
260 // Don't try to map files that are exactly a multiple of the system page size
261 // if we need a null terminator.
262 if ((FileSize
& (PageSize
-1)) == 0)
268 error_code
MemoryBuffer::getOpenFile(int FD
, const char *Filename
,
269 OwningPtr
<MemoryBuffer
> &result
,
270 size_t FileSize
, size_t MapSize
,
272 bool RequiresNullTerminator
) {
273 static int PageSize
= sys::Process::GetPageSize();
275 // Default is to map the full file.
276 if (MapSize
== size_t(-1)) {
277 // If we don't know the file size, use fstat to find out. fstat on an open
278 // file descriptor is cheaper than stat on a random path.
279 if (FileSize
== size_t(-1)) {
280 struct stat FileInfo
;
281 // TODO: This should use fstat64 when available.
282 if (fstat(FD
, &FileInfo
) == -1) {
283 return error_code(errno
, posix_category());
285 FileSize
= FileInfo
.st_size
;
290 if (shouldUseMmap(FD
, FileSize
, MapSize
, Offset
, RequiresNullTerminator
,
292 off_t RealMapOffset
= Offset
& ~(PageSize
- 1);
293 off_t Delta
= Offset
- RealMapOffset
;
294 size_t RealMapSize
= MapSize
+ Delta
;
296 if (const char *Pages
= sys::Path::MapInFilePages(FD
,
299 result
.reset(GetNamedBuffer
<MemoryBufferMMapFile
>(
300 StringRef(Pages
+ Delta
, MapSize
), Filename
, RequiresNullTerminator
));
305 MemoryBuffer
*Buf
= MemoryBuffer::getNewUninitMemBuffer(MapSize
, Filename
);
307 // Failed to create a buffer. The only way it can fail is if
308 // new(std::nothrow) returns 0.
309 return make_error_code(errc::not_enough_memory
);
312 OwningPtr
<MemoryBuffer
> SB(Buf
);
313 char *BufPtr
= const_cast<char*>(SB
->getBufferStart());
315 size_t BytesLeft
= MapSize
;
316 if (lseek(FD
, Offset
, SEEK_SET
) == -1)
317 return error_code(errno
, posix_category());
320 ssize_t NumRead
= ::read(FD
, BufPtr
, BytesLeft
);
324 // Error while reading.
325 return error_code(errno
, posix_category());
326 } else if (NumRead
== 0) {
327 // We hit EOF early, truncate and terminate buffer.
328 Buf
->BufferEnd
= BufPtr
;
333 BytesLeft
-= NumRead
;
341 //===----------------------------------------------------------------------===//
342 // MemoryBuffer::getSTDIN implementation.
343 //===----------------------------------------------------------------------===//
345 error_code
MemoryBuffer::getSTDIN(OwningPtr
<MemoryBuffer
> &result
) {
346 // Read in all of the data from stdin, we cannot mmap stdin.
348 // FIXME: That isn't necessarily true, we should try to mmap stdin and
349 // fallback if it fails.
350 sys::Program::ChangeStdinToBinary();
352 const ssize_t ChunkSize
= 4096*4;
353 SmallString
<ChunkSize
> Buffer
;
355 // Read into Buffer until we hit EOF.
357 Buffer
.reserve(Buffer
.size() + ChunkSize
);
358 ReadBytes
= read(0, Buffer
.end(), ChunkSize
);
359 if (ReadBytes
== -1) {
360 if (errno
== EINTR
) continue;
361 return error_code(errno
, posix_category());
363 Buffer
.set_size(Buffer
.size() + ReadBytes
);
364 } while (ReadBytes
!= 0);
366 result
.reset(getMemBufferCopy(Buffer
, "<stdin>"));