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/Errno.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/MathExtras.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"
31 #include <sys/types.h>
32 #if !defined(_MSC_VER) && !defined(__MINGW32__)
36 // Simplistic definitinos of these macros to allow files to be read with
39 #define S_ISREG(x) (1)
42 #define S_ISBLK(x) (0)
48 //===----------------------------------------------------------------------===//
49 // MemoryBuffer implementation itself.
50 //===----------------------------------------------------------------------===//
52 MemoryBuffer::~MemoryBuffer() { }
54 /// init - Initialize this MemoryBuffer as a reference to externally allocated
55 /// memory, memory that we know is already null terminated.
56 void MemoryBuffer::init(const char *BufStart, const char *BufEnd,
57 bool RequiresNullTerminator) {
58 assert((!RequiresNullTerminator || BufEnd[0] == 0) &&
59 "Buffer is not null terminated!");
60 BufferStart = BufStart;
64 //===----------------------------------------------------------------------===//
65 // MemoryBufferMem implementation.
66 //===----------------------------------------------------------------------===//
68 /// CopyStringRef - Copies contents of a StringRef into a block of memory and
69 /// null-terminates it.
70 static void CopyStringRef(char *Memory, StringRef Data) {
71 memcpy(Memory, Data.data(), Data.size());
72 Memory[Data.size()] = 0; // Null terminate string.
75 /// GetNamedBuffer - Allocates a new MemoryBuffer with Name copied after it.
77 static T *GetNamedBuffer(StringRef Buffer, StringRef Name,
78 bool RequiresNullTerminator) {
79 char *Mem = static_cast<char*>(operator new(sizeof(T) + Name.size() + 1));
80 CopyStringRef(Mem + sizeof(T), Name);
81 return new (Mem) T(Buffer, RequiresNullTerminator);
85 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
86 class MemoryBufferMem : public MemoryBuffer {
88 MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
89 init(InputData.begin(), InputData.end(), RequiresNullTerminator);
92 virtual const char *getBufferIdentifier() const LLVM_OVERRIDE {
93 // The name is stored after the class itself.
94 return reinterpret_cast<const char*>(this + 1);
97 virtual BufferKind getBufferKind() const LLVM_OVERRIDE {
98 return MemoryBuffer_Malloc;
103 /// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note
104 /// that InputData must be a null terminated if RequiresNullTerminator is true!
105 MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
106 StringRef BufferName,
107 bool RequiresNullTerminator) {
108 return GetNamedBuffer<MemoryBufferMem>(InputData, BufferName,
109 RequiresNullTerminator);
112 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
113 /// copying the contents and taking ownership of it. This has no requirements
115 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
116 StringRef BufferName) {
117 MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
119 memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
124 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
125 /// that is not initialized. Note that the caller should initialize the
126 /// memory allocated by this method. The memory is owned by the MemoryBuffer
128 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
129 StringRef BufferName) {
130 // Allocate space for the MemoryBuffer, the data and the name. It is important
131 // that MemoryBuffer and data are aligned so PointerIntPair works with them.
132 size_t AlignedStringLen =
133 RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1,
134 sizeof(void*)); // TODO: Is sizeof(void*) enough?
135 size_t RealLen = AlignedStringLen + Size + 1;
136 char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
139 // The name is stored after the class itself.
140 CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
142 // The buffer begins after the name and must be aligned.
143 char *Buf = Mem + AlignedStringLen;
144 Buf[Size] = 0; // Null terminate buffer.
146 return new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
149 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
150 /// is completely initialized to zeros. Note that the caller should
151 /// initialize the memory allocated by this method. The memory is owned by
152 /// the MemoryBuffer object.
153 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
154 MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
156 memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
161 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
162 /// if the Filename is "-". If an error occurs, this returns null and fills
163 /// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
164 /// returns an empty buffer.
165 error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
166 OwningPtr<MemoryBuffer> &result,
169 return getSTDIN(result);
170 return getFile(Filename, result, FileSize);
173 error_code MemoryBuffer::getFileOrSTDIN(const char *Filename,
174 OwningPtr<MemoryBuffer> &result,
176 if (strcmp(Filename, "-") == 0)
177 return getSTDIN(result);
178 return getFile(Filename, result, FileSize);
181 //===----------------------------------------------------------------------===//
182 // MemoryBuffer::getFile implementation.
183 //===----------------------------------------------------------------------===//
186 /// MemoryBufferMMapFile - This represents a file that was mapped in with the
187 /// sys::Path::MapInFilePages method. When destroyed, it calls the
188 /// sys::Path::UnMapFilePages method.
189 class MemoryBufferMMapFile : public MemoryBufferMem {
191 MemoryBufferMMapFile(StringRef Buffer, bool RequiresNullTerminator)
192 : MemoryBufferMem(Buffer, RequiresNullTerminator) { }
194 ~MemoryBufferMMapFile() {
195 static int PageSize = sys::process::get_self()->page_size();
197 uintptr_t Start = reinterpret_cast<uintptr_t>(getBufferStart());
198 size_t Size = getBufferSize();
199 uintptr_t RealStart = Start & ~(PageSize - 1);
200 size_t RealSize = Size + (Start - RealStart);
202 sys::Path::UnMapFilePages(reinterpret_cast<const char*>(RealStart),
206 virtual BufferKind getBufferKind() const LLVM_OVERRIDE {
207 return MemoryBuffer_MMap;
212 static error_code getMemoryBufferForStream(int FD,
213 StringRef BufferName,
214 OwningPtr<MemoryBuffer> &result) {
215 const ssize_t ChunkSize = 4096*4;
216 SmallString<ChunkSize> Buffer;
218 // Read into Buffer until we hit EOF.
220 Buffer.reserve(Buffer.size() + ChunkSize);
221 ReadBytes = read(FD, Buffer.end(), ChunkSize);
222 if (ReadBytes == -1) {
223 if (errno == EINTR) continue;
224 return error_code(errno, posix_category());
226 Buffer.set_size(Buffer.size() + ReadBytes);
227 } while (ReadBytes != 0);
229 result.reset(MemoryBuffer::getMemBufferCopy(Buffer, BufferName));
230 return error_code::success();
233 error_code MemoryBuffer::getFile(StringRef Filename,
234 OwningPtr<MemoryBuffer> &result,
236 bool RequiresNullTerminator) {
237 // Ensure the path is null terminated.
238 SmallString<256> PathBuf(Filename.begin(), Filename.end());
239 return MemoryBuffer::getFile(PathBuf.c_str(), result, FileSize,
240 RequiresNullTerminator);
243 error_code MemoryBuffer::getFile(const char *Filename,
244 OwningPtr<MemoryBuffer> &result,
246 bool RequiresNullTerminator) {
247 // FIXME: Review if this check is unnecessary on windows as well.
249 // First check that the "file" is not a directory
251 error_code err = sys::fs::is_directory(Filename, is_dir);
255 return make_error_code(errc::is_a_directory);
258 int OpenFlags = O_RDONLY;
260 OpenFlags |= O_BINARY; // Open input file in binary mode on win32.
262 int FD = ::open(Filename, OpenFlags);
264 return error_code(errno, posix_category());
266 error_code ret = getOpenFile(FD, Filename, result, FileSize, FileSize,
267 0, RequiresNullTerminator);
272 static bool shouldUseMmap(int FD,
276 bool RequiresNullTerminator,
278 // We don't use mmap for small files because this can severely fragment our
280 if (MapSize < 4096*4)
283 if (!RequiresNullTerminator)
287 // If we don't know the file size, use fstat to find out. fstat on an open
288 // file descriptor is cheaper than stat on a random path.
289 // FIXME: this chunk of code is duplicated, but it avoids a fstat when
290 // RequiresNullTerminator = false and MapSize != -1.
291 if (FileSize == size_t(-1)) {
292 struct stat FileInfo;
293 // TODO: This should use fstat64 when available.
294 if (fstat(FD, &FileInfo) == -1) {
295 return error_code(errno, posix_category());
297 FileSize = FileInfo.st_size;
300 // If we need a null terminator and the end of the map is inside the file,
301 // we cannot use mmap.
302 size_t End = Offset + MapSize;
303 assert(End <= FileSize);
307 // Don't try to map files that are exactly a multiple of the system page size
308 // if we need a null terminator.
309 if ((FileSize & (PageSize -1)) == 0)
315 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
316 OwningPtr<MemoryBuffer> &result,
317 uint64_t FileSize, uint64_t MapSize,
319 bool RequiresNullTerminator) {
320 static int PageSize = sys::process::get_self()->page_size();
322 // Default is to map the full file.
323 if (MapSize == uint64_t(-1)) {
324 // If we don't know the file size, use fstat to find out. fstat on an open
325 // file descriptor is cheaper than stat on a random path.
326 if (FileSize == uint64_t(-1)) {
327 struct stat FileInfo;
328 // TODO: This should use fstat64 when available.
329 if (fstat(FD, &FileInfo) == -1) {
330 return error_code(errno, posix_category());
333 // If this not a file or a block device (e.g. it's a named pipe
334 // or character device), we can't trust the size. Create the memory
335 // buffer by copying off the stream.
336 if (!S_ISREG(FileInfo.st_mode) && !S_ISBLK(FileInfo.st_mode)) {
337 return getMemoryBufferForStream(FD, Filename, result);
340 FileSize = FileInfo.st_size;
345 if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
347 off_t RealMapOffset = Offset & ~(PageSize - 1);
348 off_t Delta = Offset - RealMapOffset;
349 size_t RealMapSize = MapSize + Delta;
351 if (const char *Pages = sys::Path::MapInFilePages(FD,
354 result.reset(GetNamedBuffer<MemoryBufferMMapFile>(
355 StringRef(Pages + Delta, MapSize), Filename, RequiresNullTerminator));
356 return error_code::success();
360 MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
362 // Failed to create a buffer. The only way it can fail is if
363 // new(std::nothrow) returns 0.
364 return make_error_code(errc::not_enough_memory);
367 OwningPtr<MemoryBuffer> SB(Buf);
368 char *BufPtr = const_cast<char*>(SB->getBufferStart());
370 size_t BytesLeft = MapSize;
372 if (lseek(FD, Offset, SEEK_SET) == -1)
373 return error_code(errno, posix_category());
378 ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset);
380 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
385 // Error while reading.
386 return error_code(errno, posix_category());
389 assert(0 && "We got inaccurate FileSize value or fstat reported an "
390 "invalid file size.");
391 *BufPtr = '\0'; // null-terminate at the actual size.
394 BytesLeft -= NumRead;
399 return error_code::success();
402 //===----------------------------------------------------------------------===//
403 // MemoryBuffer::getSTDIN implementation.
404 //===----------------------------------------------------------------------===//
406 error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &result) {
407 // Read in all of the data from stdin, we cannot mmap stdin.
409 // FIXME: That isn't necessarily true, we should try to mmap stdin and
410 // fallback if it fails.
411 sys::Program::ChangeStdinToBinary();
413 return getMemoryBufferForStream(0, "<stdin>", result);