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/Config/config.h"
18 #include "llvm/Support/MathExtras.h"
19 #include "llvm/Support/Errno.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/Path.h"
22 #include "llvm/Support/Process.h"
23 #include "llvm/Support/Program.h"
24 #include "llvm/Support/system_error.h"
30 #include <sys/types.h>
32 #if !defined(_MSC_VER) && !defined(__MINGW32__)
37 #define S_ISFIFO(x) (0)
43 //===----------------------------------------------------------------------===//
44 // MemoryBuffer implementation itself.
45 //===----------------------------------------------------------------------===//
47 MemoryBuffer::~MemoryBuffer() { }
49 /// init - Initialize this MemoryBuffer as a reference to externally allocated
50 /// memory, memory that we know is already null terminated.
51 void MemoryBuffer::init(const char *BufStart, const char *BufEnd,
52 bool RequiresNullTerminator) {
53 assert((!RequiresNullTerminator || BufEnd[0] == 0) &&
54 "Buffer is not null terminated!");
55 BufferStart = BufStart;
59 //===----------------------------------------------------------------------===//
60 // MemoryBufferMem implementation.
61 //===----------------------------------------------------------------------===//
63 /// CopyStringRef - Copies contents of a StringRef into a block of memory and
64 /// null-terminates it.
65 static void CopyStringRef(char *Memory, StringRef Data) {
66 memcpy(Memory, Data.data(), Data.size());
67 Memory[Data.size()] = 0; // Null terminate string.
70 /// GetNamedBuffer - Allocates a new MemoryBuffer with Name copied after it.
72 static T *GetNamedBuffer(StringRef Buffer, StringRef Name,
73 bool RequiresNullTerminator) {
74 char *Mem = static_cast<char*>(operator new(sizeof(T) + Name.size() + 1));
75 CopyStringRef(Mem + sizeof(T), Name);
76 return new (Mem) T(Buffer, RequiresNullTerminator);
80 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
81 class MemoryBufferMem : public MemoryBuffer {
83 MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
84 init(InputData.begin(), InputData.end(), RequiresNullTerminator);
87 virtual const char *getBufferIdentifier() const LLVM_OVERRIDE {
88 // The name is stored after the class itself.
89 return reinterpret_cast<const char*>(this + 1);
92 virtual BufferKind getBufferKind() const LLVM_OVERRIDE {
93 return MemoryBuffer_Malloc;
98 /// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note
99 /// that InputData must be a null terminated if RequiresNullTerminator is true!
100 MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
101 StringRef BufferName,
102 bool RequiresNullTerminator) {
103 return GetNamedBuffer<MemoryBufferMem>(InputData, BufferName,
104 RequiresNullTerminator);
107 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
108 /// copying the contents and taking ownership of it. This has no requirements
110 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
111 StringRef BufferName) {
112 MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
114 memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
119 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
120 /// that is not initialized. Note that the caller should initialize the
121 /// memory allocated by this method. The memory is owned by the MemoryBuffer
123 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
124 StringRef BufferName) {
125 // Allocate space for the MemoryBuffer, the data and the name. It is important
126 // that MemoryBuffer and data are aligned so PointerIntPair works with them.
127 size_t AlignedStringLen =
128 RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1,
129 sizeof(void*)); // TODO: Is sizeof(void*) enough?
130 size_t RealLen = AlignedStringLen + Size + 1;
131 char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
134 // The name is stored after the class itself.
135 CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
137 // The buffer begins after the name and must be aligned.
138 char *Buf = Mem + AlignedStringLen;
139 Buf[Size] = 0; // Null terminate buffer.
141 return new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
144 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
145 /// is completely initialized to zeros. Note that the caller should
146 /// initialize the memory allocated by this method. The memory is owned by
147 /// the MemoryBuffer object.
148 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
149 MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
151 memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
156 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
157 /// if the Filename is "-". If an error occurs, this returns null and fills
158 /// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
159 /// returns an empty buffer.
160 error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
161 OwningPtr<MemoryBuffer> &result,
164 return getSTDIN(result);
165 return getFile(Filename, result, FileSize);
168 error_code MemoryBuffer::getFileOrSTDIN(const char *Filename,
169 OwningPtr<MemoryBuffer> &result,
171 if (strcmp(Filename, "-") == 0)
172 return getSTDIN(result);
173 return getFile(Filename, result, FileSize);
176 //===----------------------------------------------------------------------===//
177 // MemoryBuffer::getFile implementation.
178 //===----------------------------------------------------------------------===//
181 /// MemoryBufferMMapFile - This represents a file that was mapped in with the
182 /// sys::Path::MapInFilePages method. When destroyed, it calls the
183 /// sys::Path::UnMapFilePages method.
184 class MemoryBufferMMapFile : public MemoryBufferMem {
186 MemoryBufferMMapFile(StringRef Buffer, bool RequiresNullTerminator)
187 : MemoryBufferMem(Buffer, RequiresNullTerminator) { }
189 ~MemoryBufferMMapFile() {
190 static int PageSize = sys::Process::GetPageSize();
192 uintptr_t Start = reinterpret_cast<uintptr_t>(getBufferStart());
193 size_t Size = getBufferSize();
194 uintptr_t RealStart = Start & ~(PageSize - 1);
195 size_t RealSize = Size + (Start - RealStart);
197 sys::Path::UnMapFilePages(reinterpret_cast<const char*>(RealStart),
201 virtual BufferKind getBufferKind() const LLVM_OVERRIDE {
202 return MemoryBuffer_MMap;
207 static error_code getMemoryBufferForStream(int FD,
208 StringRef BufferName,
209 OwningPtr<MemoryBuffer> &result) {
210 const ssize_t ChunkSize = 4096*4;
211 SmallString<ChunkSize> Buffer;
213 // Read into Buffer until we hit EOF.
215 Buffer.reserve(Buffer.size() + ChunkSize);
216 ReadBytes = read(FD, Buffer.end(), ChunkSize);
217 if (ReadBytes == -1) {
218 if (errno == EINTR) continue;
219 return error_code(errno, posix_category());
221 Buffer.set_size(Buffer.size() + ReadBytes);
222 } while (ReadBytes != 0);
224 result.reset(MemoryBuffer::getMemBufferCopy(Buffer, BufferName));
225 return error_code::success();
228 error_code MemoryBuffer::getFile(StringRef Filename,
229 OwningPtr<MemoryBuffer> &result,
231 bool RequiresNullTerminator) {
232 // Ensure the path is null terminated.
233 SmallString<256> PathBuf(Filename.begin(), Filename.end());
234 return MemoryBuffer::getFile(PathBuf.c_str(), result, FileSize,
235 RequiresNullTerminator);
238 error_code MemoryBuffer::getFile(const char *Filename,
239 OwningPtr<MemoryBuffer> &result,
241 bool RequiresNullTerminator) {
242 // First check that the "file" is not a directory
244 error_code err = sys::fs::is_directory(Filename, is_dir);
248 return make_error_code(errc::is_a_directory);
250 int OpenFlags = O_RDONLY;
252 OpenFlags |= O_BINARY; // Open input file in binary mode on win32.
254 int FD = ::open(Filename, OpenFlags);
256 return error_code(errno, posix_category());
258 error_code ret = getOpenFile(FD, Filename, result, FileSize, FileSize,
259 0, RequiresNullTerminator);
264 static bool shouldUseMmap(int FD,
268 bool RequiresNullTerminator,
270 // We don't use mmap for small files because this can severely fragment our
272 if (MapSize < 4096*4)
275 if (!RequiresNullTerminator)
279 // If we don't know the file size, use fstat to find out. fstat on an open
280 // file descriptor is cheaper than stat on a random path.
281 // FIXME: this chunk of code is duplicated, but it avoids a fstat when
282 // RequiresNullTerminator = false and MapSize != -1.
283 if (FileSize == size_t(-1)) {
284 struct stat FileInfo;
285 // TODO: This should use fstat64 when available.
286 if (fstat(FD, &FileInfo) == -1) {
287 return error_code(errno, posix_category());
289 FileSize = FileInfo.st_size;
292 // If we need a null terminator and the end of the map is inside the file,
293 // we cannot use mmap.
294 size_t End = Offset + MapSize;
295 assert(End <= FileSize);
299 // Don't try to map files that are exactly a multiple of the system page size
300 // if we need a null terminator.
301 if ((FileSize & (PageSize -1)) == 0)
307 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
308 OwningPtr<MemoryBuffer> &result,
309 uint64_t FileSize, uint64_t MapSize,
311 bool RequiresNullTerminator) {
312 static int PageSize = sys::Process::GetPageSize();
314 // Default is to map the full file.
315 if (MapSize == uint64_t(-1)) {
316 // If we don't know the file size, use fstat to find out. fstat on an open
317 // file descriptor is cheaper than stat on a random path.
318 if (FileSize == uint64_t(-1)) {
319 struct stat FileInfo;
320 // TODO: This should use fstat64 when available.
321 if (fstat(FD, &FileInfo) == -1) {
322 return error_code(errno, posix_category());
325 // If this is a named pipe, we can't trust the size. Create the memory
326 // buffer by copying off the stream.
327 if (S_ISFIFO(FileInfo.st_mode)) {
328 return getMemoryBufferForStream(FD, Filename, result);
331 FileSize = FileInfo.st_size;
336 if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
338 off_t RealMapOffset = Offset & ~(PageSize - 1);
339 off_t Delta = Offset - RealMapOffset;
340 size_t RealMapSize = MapSize + Delta;
342 if (const char *Pages = sys::Path::MapInFilePages(FD,
345 result.reset(GetNamedBuffer<MemoryBufferMMapFile>(
346 StringRef(Pages + Delta, MapSize), Filename, RequiresNullTerminator));
347 return error_code::success();
351 MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
353 // Failed to create a buffer. The only way it can fail is if
354 // new(std::nothrow) returns 0.
355 return make_error_code(errc::not_enough_memory);
358 OwningPtr<MemoryBuffer> SB(Buf);
359 char *BufPtr = const_cast<char*>(SB->getBufferStart());
361 size_t BytesLeft = MapSize;
363 if (lseek(FD, Offset, SEEK_SET) == -1)
364 return error_code(errno, posix_category());
369 ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset);
371 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
376 // Error while reading.
377 return error_code(errno, posix_category());
380 assert(0 && "We got inaccurate FileSize value or fstat reported an "
381 "invalid file size.");
382 *BufPtr = '\0'; // null-terminate at the actual size.
385 BytesLeft -= NumRead;
390 return error_code::success();
393 //===----------------------------------------------------------------------===//
394 // MemoryBuffer::getSTDIN implementation.
395 //===----------------------------------------------------------------------===//
397 error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &result) {
398 // Read in all of the data from stdin, we cannot mmap stdin.
400 // FIXME: That isn't necessarily true, we should try to mmap stdin and
401 // fallback if it fails.
402 sys::Program::ChangeStdinToBinary();
404 return getMemoryBufferForStream(0, "<stdin>", result);