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.
76 struct NamedBufferAlloc {
78 NamedBufferAlloc(StringRef Name) : Name(Name) {}
82 void *operator new(size_t N, const NamedBufferAlloc &Alloc) {
83 char *Mem = static_cast<char *>(operator new(N + Alloc.Name.size() + 1));
84 CopyStringRef(Mem + N, Alloc.Name);
89 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
90 class MemoryBufferMem : public MemoryBuffer {
92 MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
93 init(InputData.begin(), InputData.end(), RequiresNullTerminator);
96 virtual const char *getBufferIdentifier() const LLVM_OVERRIDE {
97 // The name is stored after the class itself.
98 return reinterpret_cast<const char*>(this + 1);
101 virtual BufferKind getBufferKind() const LLVM_OVERRIDE {
102 return MemoryBuffer_Malloc;
107 /// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note
108 /// that InputData must be a null terminated if RequiresNullTerminator is true!
109 MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
110 StringRef BufferName,
111 bool RequiresNullTerminator) {
112 return new (NamedBufferAlloc(BufferName))
113 MemoryBufferMem(InputData, RequiresNullTerminator);
116 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
117 /// copying the contents and taking ownership of it. This has no requirements
119 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
120 StringRef BufferName) {
121 MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
123 memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
128 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
129 /// that is not initialized. Note that the caller should initialize the
130 /// memory allocated by this method. The memory is owned by the MemoryBuffer
132 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
133 StringRef BufferName) {
134 // Allocate space for the MemoryBuffer, the data and the name. It is important
135 // that MemoryBuffer and data are aligned so PointerIntPair works with them.
136 size_t AlignedStringLen =
137 RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1,
138 sizeof(void*)); // TODO: Is sizeof(void*) enough?
139 size_t RealLen = AlignedStringLen + Size + 1;
140 char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
143 // The name is stored after the class itself.
144 CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
146 // The buffer begins after the name and must be aligned.
147 char *Buf = Mem + AlignedStringLen;
148 Buf[Size] = 0; // Null terminate buffer.
150 return new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
153 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
154 /// is completely initialized to zeros. Note that the caller should
155 /// initialize the memory allocated by this method. The memory is owned by
156 /// the MemoryBuffer object.
157 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
158 MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
160 memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
165 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
166 /// if the Filename is "-". If an error occurs, this returns null and fills
167 /// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
168 /// returns an empty buffer.
169 error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
170 OwningPtr<MemoryBuffer> &result,
173 return getSTDIN(result);
174 return getFile(Filename, result, FileSize);
177 error_code MemoryBuffer::getFileOrSTDIN(const char *Filename,
178 OwningPtr<MemoryBuffer> &result,
180 if (strcmp(Filename, "-") == 0)
181 return getSTDIN(result);
182 return getFile(Filename, result, FileSize);
185 //===----------------------------------------------------------------------===//
186 // MemoryBuffer::getFile implementation.
187 //===----------------------------------------------------------------------===//
190 /// \brief Memorry maps a file descriptor using sys::fs::mapped_file_region.
192 /// This handles converting the offset into a legal offset on the platform.
193 class MemoryBufferMMapFile : public MemoryBuffer {
194 sys::fs::mapped_file_region MFR;
196 static uint64_t getLegalMapOffset(uint64_t Offset) {
197 return Offset & ~(sys::fs::mapped_file_region::alignment() - 1);
200 static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) {
201 return Len + (Offset - getLegalMapOffset(Offset));
204 const char *getStart(uint64_t Len, uint64_t Offset) {
205 return MFR.const_data() + (Offset - getLegalMapOffset(Offset));
209 MemoryBufferMMapFile(bool RequiresNullTerminator, int FD, uint64_t Len,
210 uint64_t Offset, error_code EC)
211 : MFR(FD, false, sys::fs::mapped_file_region::readonly,
212 getLegalMapSize(Len, Offset), getLegalMapOffset(Offset), EC) {
214 const char *Start = getStart(Len, Offset);
215 init(Start, Start + Len, RequiresNullTerminator);
219 virtual const char *getBufferIdentifier() const LLVM_OVERRIDE {
220 // The name is stored after the class itself.
221 return reinterpret_cast<const char *>(this + 1);
224 virtual BufferKind getBufferKind() const LLVM_OVERRIDE {
225 return MemoryBuffer_MMap;
230 static error_code getMemoryBufferForStream(int FD,
231 StringRef BufferName,
232 OwningPtr<MemoryBuffer> &result) {
233 const ssize_t ChunkSize = 4096*4;
234 SmallString<ChunkSize> Buffer;
236 // Read into Buffer until we hit EOF.
238 Buffer.reserve(Buffer.size() + ChunkSize);
239 ReadBytes = read(FD, Buffer.end(), ChunkSize);
240 if (ReadBytes == -1) {
241 if (errno == EINTR) continue;
242 return error_code(errno, posix_category());
244 Buffer.set_size(Buffer.size() + ReadBytes);
245 } while (ReadBytes != 0);
247 result.reset(MemoryBuffer::getMemBufferCopy(Buffer, BufferName));
248 return error_code::success();
251 error_code MemoryBuffer::getFile(StringRef Filename,
252 OwningPtr<MemoryBuffer> &result,
254 bool RequiresNullTerminator) {
255 // Ensure the path is null terminated.
256 SmallString<256> PathBuf(Filename.begin(), Filename.end());
257 return MemoryBuffer::getFile(PathBuf.c_str(), result, FileSize,
258 RequiresNullTerminator);
261 error_code MemoryBuffer::getFile(const char *Filename,
262 OwningPtr<MemoryBuffer> &result,
264 bool RequiresNullTerminator) {
265 // FIXME: Review if this check is unnecessary on windows as well.
267 // First check that the "file" is not a directory
269 error_code err = sys::fs::is_directory(Filename, is_dir);
273 return make_error_code(errc::is_a_directory);
276 int OpenFlags = O_RDONLY;
278 OpenFlags |= O_BINARY; // Open input file in binary mode on win32.
280 int FD = ::open(Filename, OpenFlags);
282 return error_code(errno, posix_category());
284 error_code ret = getOpenFile(FD, Filename, result, FileSize, FileSize,
285 0, RequiresNullTerminator);
290 static bool shouldUseMmap(int FD,
294 bool RequiresNullTerminator,
296 // We don't use mmap for small files because this can severely fragment our
298 if (MapSize < 4096*4)
301 if (!RequiresNullTerminator)
305 // If we don't know the file size, use fstat to find out. fstat on an open
306 // file descriptor is cheaper than stat on a random path.
307 // FIXME: this chunk of code is duplicated, but it avoids a fstat when
308 // RequiresNullTerminator = false and MapSize != -1.
309 if (FileSize == size_t(-1)) {
310 struct stat FileInfo;
311 // TODO: This should use fstat64 when available.
312 if (fstat(FD, &FileInfo) == -1) {
313 return error_code(errno, posix_category());
315 FileSize = FileInfo.st_size;
318 // If we need a null terminator and the end of the map is inside the file,
319 // we cannot use mmap.
320 size_t End = Offset + MapSize;
321 assert(End <= FileSize);
325 // Don't try to map files that are exactly a multiple of the system page size
326 // if we need a null terminator.
327 if ((FileSize & (PageSize -1)) == 0)
333 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
334 OwningPtr<MemoryBuffer> &result,
335 uint64_t FileSize, uint64_t MapSize,
337 bool RequiresNullTerminator) {
338 static int PageSize = sys::process::get_self()->page_size();
340 // Default is to map the full file.
341 if (MapSize == uint64_t(-1)) {
342 // If we don't know the file size, use fstat to find out. fstat on an open
343 // file descriptor is cheaper than stat on a random path.
344 if (FileSize == uint64_t(-1)) {
345 struct stat FileInfo;
346 // TODO: This should use fstat64 when available.
347 if (fstat(FD, &FileInfo) == -1) {
348 return error_code(errno, posix_category());
351 // If this not a file or a block device (e.g. it's a named pipe
352 // or character device), we can't trust the size. Create the memory
353 // buffer by copying off the stream.
354 if (!S_ISREG(FileInfo.st_mode) && !S_ISBLK(FileInfo.st_mode)) {
355 return getMemoryBufferForStream(FD, Filename, result);
358 FileSize = FileInfo.st_size;
363 if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
366 result.reset(new (NamedBufferAlloc(Filename)) MemoryBufferMMapFile(
367 RequiresNullTerminator, FD, MapSize, Offset, EC));
369 return error_code::success();
372 MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
374 // Failed to create a buffer. The only way it can fail is if
375 // new(std::nothrow) returns 0.
376 return make_error_code(errc::not_enough_memory);
379 OwningPtr<MemoryBuffer> SB(Buf);
380 char *BufPtr = const_cast<char*>(SB->getBufferStart());
382 size_t BytesLeft = MapSize;
384 if (lseek(FD, Offset, SEEK_SET) == -1)
385 return error_code(errno, posix_category());
390 ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset);
392 ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
397 // Error while reading.
398 return error_code(errno, posix_category());
401 assert(0 && "We got inaccurate FileSize value or fstat reported an "
402 "invalid file size.");
403 *BufPtr = '\0'; // null-terminate at the actual size.
406 BytesLeft -= NumRead;
411 return error_code::success();
414 //===----------------------------------------------------------------------===//
415 // MemoryBuffer::getSTDIN implementation.
416 //===----------------------------------------------------------------------===//
418 error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &result) {
419 // Read in all of the data from stdin, we cannot mmap stdin.
421 // FIXME: That isn't necessarily true, we should try to mmap stdin and
422 // fallback if it fails.
423 sys::Program::ChangeStdinToBinary();
425 return getMemoryBufferForStream(0, "<stdin>", result);