LLVM API Documentation

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
MemoryBuffer.cpp
Go to the documentation of this file.
1 //===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the MemoryBuffer interface.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "llvm/ADT/OwningPtr.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/Config/config.h"
18 #include "llvm/Support/Errno.h"
21 #include "llvm/Support/Path.h"
22 #include "llvm/Support/Process.h"
23 #include "llvm/Support/Program.h"
25 #include <cassert>
26 #include <cerrno>
27 #include <cstdio>
28 #include <cstring>
29 #include <new>
30 #include <sys/stat.h>
31 #include <sys/types.h>
32 #if !defined(_MSC_VER) && !defined(__MINGW32__)
33 #include <unistd.h>
34 #else
35 #include <io.h>
36 // Simplistic definitinos of these macros for use in getOpenFile.
37 #ifndef S_ISREG
38 #define S_ISREG(x) (1)
39 #endif
40 #ifndef S_ISBLK
41 #define S_ISBLK(x) (0)
42 #endif
43 #endif
44 using namespace llvm;
45 
46 //===----------------------------------------------------------------------===//
47 // MemoryBuffer implementation itself.
48 //===----------------------------------------------------------------------===//
49 
51 
52 /// init - Initialize this MemoryBuffer as a reference to externally allocated
53 /// memory, memory that we know is already null terminated.
54 void MemoryBuffer::init(const char *BufStart, const char *BufEnd,
55  bool RequiresNullTerminator) {
56  assert((!RequiresNullTerminator || BufEnd[0] == 0) &&
57  "Buffer is not null terminated!");
58  BufferStart = BufStart;
59  BufferEnd = BufEnd;
60 }
61 
62 //===----------------------------------------------------------------------===//
63 // MemoryBufferMem implementation.
64 //===----------------------------------------------------------------------===//
65 
66 /// CopyStringRef - Copies contents of a StringRef into a block of memory and
67 /// null-terminates it.
68 static void CopyStringRef(char *Memory, StringRef Data) {
69  memcpy(Memory, Data.data(), Data.size());
70  Memory[Data.size()] = 0; // Null terminate string.
71 }
72 
73 namespace {
74 struct NamedBufferAlloc {
76  NamedBufferAlloc(StringRef Name) : Name(Name) {}
77 };
78 }
79 
80 void *operator new(size_t N, const NamedBufferAlloc &Alloc) {
81  char *Mem = static_cast<char *>(operator new(N + Alloc.Name.size() + 1));
82  CopyStringRef(Mem + N, Alloc.Name);
83  return Mem;
84 }
85 
86 namespace {
87 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
88 class MemoryBufferMem : public MemoryBuffer {
89 public:
90  MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
91  init(InputData.begin(), InputData.end(), RequiresNullTerminator);
92  }
93 
94  virtual const char *getBufferIdentifier() const LLVM_OVERRIDE {
95  // The name is stored after the class itself.
96  return reinterpret_cast<const char*>(this + 1);
97  }
98 
99  virtual BufferKind getBufferKind() const LLVM_OVERRIDE {
100  return MemoryBuffer_Malloc;
101  }
102 };
103 }
104 
105 /// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note
106 /// that InputData must be a null terminated if RequiresNullTerminator is true!
108  StringRef BufferName,
109  bool RequiresNullTerminator) {
110  return new (NamedBufferAlloc(BufferName))
111  MemoryBufferMem(InputData, RequiresNullTerminator);
112 }
113 
114 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
115 /// copying the contents and taking ownership of it. This has no requirements
116 /// on EndPtr[0].
118  StringRef BufferName) {
119  MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
120  if (!Buf) return 0;
121  memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
122  InputData.size());
123  return Buf;
124 }
125 
126 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
127 /// that is not initialized. Note that the caller should initialize the
128 /// memory allocated by this method. The memory is owned by the MemoryBuffer
129 /// object.
131  StringRef BufferName) {
132  // Allocate space for the MemoryBuffer, the data and the name. It is important
133  // that MemoryBuffer and data are aligned so PointerIntPair works with them.
134  size_t AlignedStringLen =
135  RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1,
136  sizeof(void*)); // TODO: Is sizeof(void*) enough?
137  size_t RealLen = AlignedStringLen + Size + 1;
138  char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
139  if (!Mem) return 0;
140 
141  // The name is stored after the class itself.
142  CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
143 
144  // The buffer begins after the name and must be aligned.
145  char *Buf = Mem + AlignedStringLen;
146  Buf[Size] = 0; // Null terminate buffer.
147 
148  return new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
149 }
150 
151 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
152 /// is completely initialized to zeros. Note that the caller should
153 /// initialize the memory allocated by this method. The memory is owned by
154 /// the MemoryBuffer object.
156  MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
157  if (!SB) return 0;
158  memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
159  return SB;
160 }
161 
162 
163 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
164 /// if the Filename is "-". If an error occurs, this returns null and fills
165 /// in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)
166 /// returns an empty buffer.
168  OwningPtr<MemoryBuffer> &result,
169  int64_t FileSize) {
170  if (Filename == "-")
171  return getSTDIN(result);
172  return getFile(Filename, result, FileSize);
173 }
174 
175 //===----------------------------------------------------------------------===//
176 // MemoryBuffer::getFile implementation.
177 //===----------------------------------------------------------------------===//
178 
179 namespace {
180 /// \brief Memory maps a file descriptor using sys::fs::mapped_file_region.
181 ///
182 /// This handles converting the offset into a legal offset on the platform.
183 class MemoryBufferMMapFile : public MemoryBuffer {
185 
186  static uint64_t getLegalMapOffset(uint64_t Offset) {
187  return Offset & ~(sys::fs::mapped_file_region::alignment() - 1);
188  }
189 
190  static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) {
191  return Len + (Offset - getLegalMapOffset(Offset));
192  }
193 
194  const char *getStart(uint64_t Len, uint64_t Offset) {
195  return MFR.const_data() + (Offset - getLegalMapOffset(Offset));
196  }
197 
198 public:
199  MemoryBufferMMapFile(bool RequiresNullTerminator, int FD, uint64_t Len,
200  uint64_t Offset, error_code EC)
201  : MFR(FD, false, sys::fs::mapped_file_region::readonly,
202  getLegalMapSize(Len, Offset), getLegalMapOffset(Offset), EC) {
203  if (!EC) {
204  const char *Start = getStart(Len, Offset);
205  init(Start, Start + Len, RequiresNullTerminator);
206  }
207  }
208 
209  virtual const char *getBufferIdentifier() const LLVM_OVERRIDE {
210  // The name is stored after the class itself.
211  return reinterpret_cast<const char *>(this + 1);
212  }
213 
214  virtual BufferKind getBufferKind() const LLVM_OVERRIDE {
215  return MemoryBuffer_MMap;
216  }
217 };
218 }
219 
221  StringRef BufferName,
222  OwningPtr<MemoryBuffer> &result) {
223  const ssize_t ChunkSize = 4096*4;
224  SmallString<ChunkSize> Buffer;
225  ssize_t ReadBytes;
226  // Read into Buffer until we hit EOF.
227  do {
228  Buffer.reserve(Buffer.size() + ChunkSize);
229  ReadBytes = read(FD, Buffer.end(), ChunkSize);
230  if (ReadBytes == -1) {
231  if (errno == EINTR) continue;
232  return error_code(errno, posix_category());
233  }
234  Buffer.set_size(Buffer.size() + ReadBytes);
235  } while (ReadBytes != 0);
236 
237  result.reset(MemoryBuffer::getMemBufferCopy(Buffer, BufferName));
238  return error_code::success();
239 }
240 
241 static error_code getFileAux(const char *Filename,
242  OwningPtr<MemoryBuffer> &result, int64_t FileSize,
243  bool RequiresNullTerminator);
244 
246  OwningPtr<MemoryBuffer> &result,
247  int64_t FileSize,
248  bool RequiresNullTerminator) {
249  // Ensure the path is null terminated.
250  SmallString<256> PathBuf;
251  StringRef NullTerminatedName = Filename.toNullTerminatedStringRef(PathBuf);
252  return getFileAux(NullTerminatedName.data(), result, FileSize,
253  RequiresNullTerminator);
254 }
255 
256 static error_code getOpenFileImpl(int FD, const char *Filename,
257  OwningPtr<MemoryBuffer> &Result,
258  uint64_t FileSize, uint64_t MapSize,
259  int64_t Offset, bool RequiresNullTerminator);
260 
261 static error_code getFileAux(const char *Filename,
262  OwningPtr<MemoryBuffer> &result, int64_t FileSize,
263  bool RequiresNullTerminator) {
264  int FD;
265  error_code EC = sys::fs::openFileForRead(Filename, FD);
266  if (EC)
267  return EC;
268 
269  error_code ret = getOpenFileImpl(FD, Filename, result, FileSize, FileSize, 0,
270  RequiresNullTerminator);
271  close(FD);
272  return ret;
273 }
274 
275 static bool shouldUseMmap(int FD,
276  size_t FileSize,
277  size_t MapSize,
278  off_t Offset,
279  bool RequiresNullTerminator,
280  int PageSize) {
281  // We don't use mmap for small files because this can severely fragment our
282  // address space.
283  if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize)
284  return false;
285 
286  if (!RequiresNullTerminator)
287  return true;
288 
289 
290  // If we don't know the file size, use fstat to find out. fstat on an open
291  // file descriptor is cheaper than stat on a random path.
292  // FIXME: this chunk of code is duplicated, but it avoids a fstat when
293  // RequiresNullTerminator = false and MapSize != -1.
294  if (FileSize == size_t(-1)) {
296  error_code EC = sys::fs::status(FD, Status);
297  if (EC)
298  return EC;
299  FileSize = Status.getSize();
300  }
301 
302  // If we need a null terminator and the end of the map is inside the file,
303  // we cannot use mmap.
304  size_t End = Offset + MapSize;
305  assert(End <= FileSize);
306  if (End != FileSize)
307  return false;
308 
309 #if defined(_WIN32) || defined(__CYGWIN__)
310  // Don't peek the next page if file is multiple of *physical* pagesize(4k)
311  // but is not multiple of AllocationGranularity(64k),
312  // when a null terminator is required.
313  // FIXME: It's not good to hardcode 4096 here. dwPageSize shows 4096.
314  if ((FileSize & (4096 - 1)) == 0)
315  return false;
316 #endif
317 
318  // Don't try to map files that are exactly a multiple of the system page size
319  // if we need a null terminator.
320  if ((FileSize & (PageSize -1)) == 0)
321  return false;
322 
323  return true;
324 }
325 
326 static error_code getOpenFileImpl(int FD, const char *Filename,
327  OwningPtr<MemoryBuffer> &result,
328  uint64_t FileSize, uint64_t MapSize,
329  int64_t Offset, bool RequiresNullTerminator) {
330  static int PageSize = sys::process::get_self()->page_size();
331 
332  // Default is to map the full file.
333  if (MapSize == uint64_t(-1)) {
334  // If we don't know the file size, use fstat to find out. fstat on an open
335  // file descriptor is cheaper than stat on a random path.
336  if (FileSize == uint64_t(-1)) {
338  error_code EC = sys::fs::status(FD, Status);
339  if (EC)
340  return EC;
341 
342  // If this not a file or a block device (e.g. it's a named pipe
343  // or character device), we can't trust the size. Create the memory
344  // buffer by copying off the stream.
345  sys::fs::file_type Type = Status.type();
346  if (Type != sys::fs::file_type::regular_file &&
348  return getMemoryBufferForStream(FD, Filename, result);
349 
350  FileSize = Status.getSize();
351  }
352  MapSize = FileSize;
353  }
354 
355  if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
356  PageSize)) {
357  error_code EC;
358  result.reset(new (NamedBufferAlloc(Filename)) MemoryBufferMMapFile(
359  RequiresNullTerminator, FD, MapSize, Offset, EC));
360  if (!EC)
361  return error_code::success();
362  }
363 
364  MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
365  if (!Buf) {
366  // Failed to create a buffer. The only way it can fail is if
367  // new(std::nothrow) returns 0.
369  }
370 
371  OwningPtr<MemoryBuffer> SB(Buf);
372  char *BufPtr = const_cast<char*>(SB->getBufferStart());
373 
374  size_t BytesLeft = MapSize;
375 #ifndef HAVE_PREAD
376  if (lseek(FD, Offset, SEEK_SET) == -1)
377  return error_code(errno, posix_category());
378 #endif
379 
380  while (BytesLeft) {
381 #ifdef HAVE_PREAD
382  ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset);
383 #else
384  ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
385 #endif
386  if (NumRead == -1) {
387  if (errno == EINTR)
388  continue;
389  // Error while reading.
390  return error_code(errno, posix_category());
391  }
392  if (NumRead == 0) {
393  assert(0 && "We got inaccurate FileSize value or fstat reported an "
394  "invalid file size.");
395  *BufPtr = '\0'; // null-terminate at the actual size.
396  break;
397  }
398  BytesLeft -= NumRead;
399  BufPtr += NumRead;
400  }
401 
402  result.swap(SB);
403  return error_code::success();
404 }
405 
406 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
407  OwningPtr<MemoryBuffer> &Result,
408  uint64_t FileSize,
409  bool RequiresNullTerminator) {
410  return getOpenFileImpl(FD, Filename, Result, FileSize, FileSize, 0,
411  RequiresNullTerminator);
412 }
413 
414 error_code MemoryBuffer::getOpenFileSlice(int FD, const char *Filename,
415  OwningPtr<MemoryBuffer> &Result,
416  uint64_t MapSize, int64_t Offset) {
417  return getOpenFileImpl(FD, Filename, Result, -1, MapSize, Offset, false);
418 }
419 
420 //===----------------------------------------------------------------------===//
421 // MemoryBuffer::getSTDIN implementation.
422 //===----------------------------------------------------------------------===//
423 
425  // Read in all of the data from stdin, we cannot mmap stdin.
426  //
427  // FIXME: That isn't necessarily true, we should try to mmap stdin and
428  // fallback if it fails.
430 
431  return getMemoryBufferForStream(0, "<stdin>", result);
432 }
static MemoryBuffer * getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
void init(const char *BufStart, const char *BufEnd, bool RequiresNullTerminator)
size_t size() const
size - Get the string size.
Definition: StringRef.h:113
const char * getBufferStart() const
Definition: MemoryBuffer.h:51
An abstraction for memory operations.
Definition: Memory.h:45
static MemoryBuffer * getNewMemBuffer(size_t Size, StringRef BufferName="")
error_code openFileForRead(const Twine &Name, int &ResultFD)
ssize_t read(int fildes, void *buf, size_t nbyte);
error_code ChangeStdinToBinary()
const char * const_data() const
static bool shouldUseMmap(int FD, size_t FileSize, size_t MapSize, off_t Offset, bool RequiresNullTerminator, int PageSize)
static error_code getOpenFileImpl(int FD, const char *Filename, OwningPtr< MemoryBuffer > &Result, uint64_t FileSize, uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator)
static error_code getOpenFile(int FD, const char *Filename, OwningPtr< MemoryBuffer > &Result, uint64_t FileSize, bool RequiresNullTerminator=true)
#define false
Definition: ConvertUTF.c:64
ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset);
const error_category & posix_category()
const char * data() const
Definition: StringRef.h:107
static void CopyStringRef(char *Memory, StringRef Data)
iterator begin() const
Definition: StringRef.h:97
static error_code getFileOrSTDIN(StringRef Filename, OwningPtr< MemoryBuffer > &result, int64_t FileSize=-1)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:314
error_code status(const Twine &path, file_status &result)
Get file status as if by POSIX stat().
void reset(T *P=0)
Definition: OwningPtr.h:51
static self_process * get_self()
Get the process object for the current process.
Definition: Process.cpp:29
static error_code getFile(Twine Filename, OwningPtr< MemoryBuffer > &result, int64_t FileSize=-1, bool RequiresNullTerminator=true)
static MemoryBuffer * getMemBufferCopy(StringRef InputData, StringRef BufferName="")
static error_code getFileAux(const char *Filename, OwningPtr< MemoryBuffer > &result, int64_t FileSize, bool RequiresNullTerminator)
static error_code getOpenFileSlice(int FD, const char *Filename, OwningPtr< MemoryBuffer > &Result, uint64_t MapSize, int64_t Offset)
uint64_t RoundUpToAlignment(uint64_t Value, uint64_t Align)
Definition: MathExtras.h:565
virtual ~MemoryBuffer()
static error_code success()
Definition: system_error.h:732
#define N
size_t page_size() const
Get the virtual memory page size.
Definition: Process.h:124
static MemoryBuffer * getNewUninitMemBuffer(size_t Size, StringRef BufferName="")
StringRef toNullTerminatedStringRef(SmallVectorImpl< char > &Out) const
Definition: Twine.cpp:38
iterator end() const
Definition: StringRef.h:99
file_type type() const
Definition: FileSystem.h:192
error_code make_error_code(errc _e)
Definition: system_error.h:782
static error_code getSTDIN(OwningPtr< MemoryBuffer > &result)
void swap(OwningPtr &RHS)
Definition: OwningPtr.h:77
static error_code getMemoryBufferForStream(int FD, StringRef BufferName, OwningPtr< MemoryBuffer > &result)
#define LLVM_OVERRIDE
Definition: Compiler.h:155