Pass a MemoryBufferRef when we can avoid taking ownership.
[oota-llvm.git] / lib / Support / MemoryBuffer.cpp
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
14 #include "llvm/Support/MemoryBuffer.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/Config/config.h"
17 #include "llvm/Support/Errc.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 <cassert>
25 #include <cerrno>
26 #include <cstdio>
27 #include <cstring>
28 #include <new>
29 #include <sys/types.h>
30 #include <system_error>
31 #if !defined(_MSC_VER) && !defined(__MINGW32__)
32 #include <unistd.h>
33 #else
34 #include <io.h>
35 #endif
36 using namespace llvm;
37
38 //===----------------------------------------------------------------------===//
39 // MemoryBuffer implementation itself.
40 //===----------------------------------------------------------------------===//
41
42 MemoryBuffer::~MemoryBuffer() { }
43
44 /// init - Initialize this MemoryBuffer as a reference to externally allocated
45 /// memory, memory that we know is already null terminated.
46 void MemoryBuffer::init(const char *BufStart, const char *BufEnd,
47                         bool RequiresNullTerminator) {
48   assert((!RequiresNullTerminator || BufEnd[0] == 0) &&
49          "Buffer is not null terminated!");
50   BufferStart = BufStart;
51   BufferEnd = BufEnd;
52 }
53
54 //===----------------------------------------------------------------------===//
55 // MemoryBufferMem implementation.
56 //===----------------------------------------------------------------------===//
57
58 /// CopyStringRef - Copies contents of a StringRef into a block of memory and
59 /// null-terminates it.
60 static void CopyStringRef(char *Memory, StringRef Data) {
61   memcpy(Memory, Data.data(), Data.size());
62   Memory[Data.size()] = 0; // Null terminate string.
63 }
64
65 namespace {
66 struct NamedBufferAlloc {
67   StringRef Name;
68   NamedBufferAlloc(StringRef Name) : Name(Name) {}
69 };
70 }
71
72 void *operator new(size_t N, const NamedBufferAlloc &Alloc) {
73   char *Mem = static_cast<char *>(operator new(N + Alloc.Name.size() + 1));
74   CopyStringRef(Mem + N, Alloc.Name);
75   return Mem;
76 }
77
78 namespace {
79 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
80 class MemoryBufferMem : public MemoryBuffer {
81 public:
82   MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
83     init(InputData.begin(), InputData.end(), RequiresNullTerminator);
84   }
85
86   const char *getBufferIdentifier() const override {
87      // The name is stored after the class itself.
88     return reinterpret_cast<const char*>(this + 1);
89   }
90
91   BufferKind getBufferKind() const override {
92     return MemoryBuffer_Malloc;
93   }
94 };
95 }
96
97 /// getMemBuffer - Open the specified memory range as a MemoryBuffer.  Note
98 /// that InputData must be a null terminated if RequiresNullTerminator is true!
99 MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
100                                          StringRef BufferName,
101                                          bool RequiresNullTerminator) {
102   return new (NamedBufferAlloc(BufferName))
103       MemoryBufferMem(InputData, RequiresNullTerminator);
104 }
105
106 std::unique_ptr<MemoryBuffer>
107 MemoryBuffer::getMemBuffer(MemoryBufferRef Ref, bool RequiresNullTerminator) {
108   return std::unique_ptr<MemoryBuffer>(getMemBuffer(
109       Ref.getBuffer(), Ref.getBufferIdentifier(), RequiresNullTerminator));
110 }
111
112 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
113 /// copying the contents and taking ownership of it.  This has no requirements
114 /// on EndPtr[0].
115 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
116                                              StringRef BufferName) {
117   MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
118   if (!Buf) return nullptr;
119   memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
120          InputData.size());
121   return Buf;
122 }
123
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
127 /// object.
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   // TODO: Is 16-byte alignment enough?  We copy small object files with large
133   // alignment expectations into this buffer.
134   size_t AlignedStringLen =
135       RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1, 16);
136   size_t RealLen = AlignedStringLen + Size + 1;
137   char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
138   if (!Mem) return nullptr;
139
140   // The name is stored after the class itself.
141   CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
142
143   // The buffer begins after the name and must be aligned.
144   char *Buf = Mem + AlignedStringLen;
145   Buf[Size] = 0; // Null terminate buffer.
146
147   return new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
148 }
149
150 /// getNewMemBuffer - Allocate a new zero-initialized MemoryBuffer of the
151 /// specified size. Note that the caller need not initialize the memory
152 /// allocated by this method.  The memory is owned by the MemoryBuffer object.
153 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
154   MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
155   if (!SB) return nullptr;
156   memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
157   return SB;
158 }
159
160 ErrorOr<std::unique_ptr<MemoryBuffer>>
161 MemoryBuffer::getFileOrSTDIN(StringRef Filename, int64_t FileSize) {
162   if (Filename == "-")
163     return getSTDIN();
164   return getFile(Filename, FileSize);
165 }
166
167
168 //===----------------------------------------------------------------------===//
169 // MemoryBuffer::getFile implementation.
170 //===----------------------------------------------------------------------===//
171
172 namespace {
173 /// \brief Memory maps a file descriptor using sys::fs::mapped_file_region.
174 ///
175 /// This handles converting the offset into a legal offset on the platform.
176 class MemoryBufferMMapFile : public MemoryBuffer {
177   sys::fs::mapped_file_region MFR;
178
179   static uint64_t getLegalMapOffset(uint64_t Offset) {
180     return Offset & ~(sys::fs::mapped_file_region::alignment() - 1);
181   }
182
183   static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) {
184     return Len + (Offset - getLegalMapOffset(Offset));
185   }
186
187   const char *getStart(uint64_t Len, uint64_t Offset) {
188     return MFR.const_data() + (Offset - getLegalMapOffset(Offset));
189   }
190
191 public:
192   MemoryBufferMMapFile(bool RequiresNullTerminator, int FD, uint64_t Len,
193                        uint64_t Offset, std::error_code EC)
194       : MFR(FD, false, sys::fs::mapped_file_region::readonly,
195             getLegalMapSize(Len, Offset), getLegalMapOffset(Offset), EC) {
196     if (!EC) {
197       const char *Start = getStart(Len, Offset);
198       init(Start, Start + Len, RequiresNullTerminator);
199     }
200   }
201
202   const char *getBufferIdentifier() const override {
203     // The name is stored after the class itself.
204     return reinterpret_cast<const char *>(this + 1);
205   }
206
207   BufferKind getBufferKind() const override {
208     return MemoryBuffer_MMap;
209   }
210 };
211 }
212
213 static ErrorOr<std::unique_ptr<MemoryBuffer>>
214 getMemoryBufferForStream(int FD, StringRef BufferName) {
215   const ssize_t ChunkSize = 4096*4;
216   SmallString<ChunkSize> Buffer;
217   ssize_t ReadBytes;
218   // Read into Buffer until we hit EOF.
219   do {
220     Buffer.reserve(Buffer.size() + ChunkSize);
221     ReadBytes = read(FD, Buffer.end(), ChunkSize);
222     if (ReadBytes == -1) {
223       if (errno == EINTR) continue;
224       return std::error_code(errno, std::generic_category());
225     }
226     Buffer.set_size(Buffer.size() + ReadBytes);
227   } while (ReadBytes != 0);
228
229   std::unique_ptr<MemoryBuffer> Ret(
230       MemoryBuffer::getMemBufferCopy(Buffer, BufferName));
231   return std::move(Ret);
232 }
233
234 static ErrorOr<std::unique_ptr<MemoryBuffer>>
235 getFileAux(const char *Filename, int64_t FileSize, bool RequiresNullTerminator,
236            bool IsVolatileSize);
237
238 ErrorOr<std::unique_ptr<MemoryBuffer>>
239 MemoryBuffer::getFile(Twine Filename, int64_t FileSize,
240                       bool RequiresNullTerminator, bool IsVolatileSize) {
241   // Ensure the path is null terminated.
242   SmallString<256> PathBuf;
243   StringRef NullTerminatedName = Filename.toNullTerminatedStringRef(PathBuf);
244   return getFileAux(NullTerminatedName.data(), FileSize, RequiresNullTerminator,
245                     IsVolatileSize);
246 }
247
248 static ErrorOr<std::unique_ptr<MemoryBuffer>>
249 getOpenFileImpl(int FD, const char *Filename, uint64_t FileSize,
250                 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
251                 bool IsVolatileSize);
252
253 static ErrorOr<std::unique_ptr<MemoryBuffer>>
254 getFileAux(const char *Filename, int64_t FileSize, bool RequiresNullTerminator,
255            bool IsVolatileSize) {
256   int FD;
257   std::error_code EC = sys::fs::openFileForRead(Filename, FD);
258   if (EC)
259     return EC;
260
261   ErrorOr<std::unique_ptr<MemoryBuffer>> Ret =
262       getOpenFileImpl(FD, Filename, FileSize, FileSize, 0,
263                       RequiresNullTerminator, IsVolatileSize);
264   close(FD);
265   return Ret;
266 }
267
268 static bool shouldUseMmap(int FD,
269                           size_t FileSize,
270                           size_t MapSize,
271                           off_t Offset,
272                           bool RequiresNullTerminator,
273                           int PageSize,
274                           bool IsVolatileSize) {
275   // mmap may leave the buffer without null terminator if the file size changed
276   // by the time the last page is mapped in, so avoid it if the file size is
277   // likely to change.
278   if (IsVolatileSize)
279     return false;
280
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)) {
295     sys::fs::file_status Status;
296     if (sys::fs::status(FD, Status))
297       return false;
298     FileSize = Status.getSize();
299   }
300
301   // If we need a null terminator and the end of the map is inside the file,
302   // we cannot use mmap.
303   size_t End = Offset + MapSize;
304   assert(End <= FileSize);
305   if (End != FileSize)
306     return false;
307
308   // Don't try to map files that are exactly a multiple of the system page size
309   // if we need a null terminator.
310   if ((FileSize & (PageSize -1)) == 0)
311     return false;
312
313 #if defined(__CYGWIN__)
314   // Don't try to map files that are exactly a multiple of the physical page size
315   // if we need a null terminator.
316   // FIXME: We should reorganize again getPageSize() on Win32.
317   if ((FileSize & (4096 - 1)) == 0)
318     return false;
319 #endif
320
321   return true;
322 }
323
324 static ErrorOr<std::unique_ptr<MemoryBuffer>>
325 getOpenFileImpl(int FD, const char *Filename, uint64_t FileSize,
326                 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
327                 bool IsVolatileSize) {
328   static int PageSize = sys::process::get_self()->page_size();
329
330   // Default is to map the full file.
331   if (MapSize == uint64_t(-1)) {
332     // If we don't know the file size, use fstat to find out.  fstat on an open
333     // file descriptor is cheaper than stat on a random path.
334     if (FileSize == uint64_t(-1)) {
335       sys::fs::file_status Status;
336       std::error_code EC = sys::fs::status(FD, Status);
337       if (EC)
338         return EC;
339
340       // If this not a file or a block device (e.g. it's a named pipe
341       // or character device), we can't trust the size. Create the memory
342       // buffer by copying off the stream.
343       sys::fs::file_type Type = Status.type();
344       if (Type != sys::fs::file_type::regular_file &&
345           Type != sys::fs::file_type::block_file)
346         return getMemoryBufferForStream(FD, Filename);
347
348       FileSize = Status.getSize();
349     }
350     MapSize = FileSize;
351   }
352
353   if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
354                     PageSize, IsVolatileSize)) {
355     std::error_code EC;
356     std::unique_ptr<MemoryBuffer> Result(
357         new (NamedBufferAlloc(Filename))
358         MemoryBufferMMapFile(RequiresNullTerminator, FD, MapSize, Offset, EC));
359     if (!EC)
360       return std::move(Result);
361   }
362
363   MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
364   if (!Buf) {
365     // Failed to create a buffer. The only way it can fail is if
366     // new(std::nothrow) returns 0.
367     return make_error_code(errc::not_enough_memory);
368   }
369
370   std::unique_ptr<MemoryBuffer> SB(Buf);
371   char *BufPtr = const_cast<char*>(SB->getBufferStart());
372
373   size_t BytesLeft = MapSize;
374 #ifndef HAVE_PREAD
375   if (lseek(FD, Offset, SEEK_SET) == -1)
376     return std::error_code(errno, std::generic_category());
377 #endif
378
379   while (BytesLeft) {
380 #ifdef HAVE_PREAD
381     ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset);
382 #else
383     ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
384 #endif
385     if (NumRead == -1) {
386       if (errno == EINTR)
387         continue;
388       // Error while reading.
389       return std::error_code(errno, std::generic_category());
390     }
391     if (NumRead == 0) {
392       memset(BufPtr, 0, BytesLeft); // zero-initialize rest of the buffer.
393       break;
394     }
395     BytesLeft -= NumRead;
396     BufPtr += NumRead;
397   }
398
399   return std::move(SB);
400 }
401
402 ErrorOr<std::unique_ptr<MemoryBuffer>>
403 MemoryBuffer::getOpenFile(int FD, const char *Filename, uint64_t FileSize,
404                           bool RequiresNullTerminator, bool IsVolatileSize) {
405   return getOpenFileImpl(FD, Filename, FileSize, FileSize, 0,
406                          RequiresNullTerminator, IsVolatileSize);
407 }
408
409 ErrorOr<std::unique_ptr<MemoryBuffer>>
410 MemoryBuffer::getOpenFileSlice(int FD, const char *Filename, uint64_t MapSize,
411                                int64_t Offset, bool IsVolatileSize) {
412   return getOpenFileImpl(FD, Filename, -1, MapSize, Offset, false,
413                          IsVolatileSize);
414 }
415
416 ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getSTDIN() {
417   // Read in all of the data from stdin, we cannot mmap stdin.
418   //
419   // FIXME: That isn't necessarily true, we should try to mmap stdin and
420   // fallback if it fails.
421   sys::ChangeStdinToBinary();
422
423   return getMemoryBufferForStream(0, "<stdin>");
424 }
425
426 MemoryBufferRef MemoryBuffer::getMemBufferRef() const {
427   StringRef Data = getBuffer();
428   StringRef Identifier = getBufferIdentifier();
429   return MemoryBufferRef(Data, Identifier);
430 }