Remove the IsVolatileSize parameter of getOpenFileSlice.
[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   const Twine &Name;
68   NamedBufferAlloc(const Twine &Name) : Name(Name) {}
69 };
70 }
71
72 void *operator new(size_t N, const NamedBufferAlloc &Alloc) {
73   SmallString<256> NameBuf;
74   StringRef NameRef = Alloc.Name.toStringRef(NameBuf);
75
76   char *Mem = static_cast<char *>(operator new(N + NameRef.size() + 1));
77   CopyStringRef(Mem + N, NameRef);
78   return Mem;
79 }
80
81 namespace {
82 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
83 class MemoryBufferMem : public MemoryBuffer {
84 public:
85   MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
86     init(InputData.begin(), InputData.end(), RequiresNullTerminator);
87   }
88
89   const char *getBufferIdentifier() const override {
90      // The name is stored after the class itself.
91     return reinterpret_cast<const char*>(this + 1);
92   }
93
94   BufferKind getBufferKind() const override {
95     return MemoryBuffer_Malloc;
96   }
97 };
98 }
99
100 std::unique_ptr<MemoryBuffer>
101 MemoryBuffer::getMemBuffer(StringRef InputData, StringRef BufferName,
102                            bool RequiresNullTerminator) {
103   auto *Ret = new (NamedBufferAlloc(BufferName))
104       MemoryBufferMem(InputData, RequiresNullTerminator);
105   return std::unique_ptr<MemoryBuffer>(Ret);
106 }
107
108 std::unique_ptr<MemoryBuffer>
109 MemoryBuffer::getMemBuffer(MemoryBufferRef Ref, bool RequiresNullTerminator) {
110   return std::unique_ptr<MemoryBuffer>(getMemBuffer(
111       Ref.getBuffer(), Ref.getBufferIdentifier(), RequiresNullTerminator));
112 }
113
114 std::unique_ptr<MemoryBuffer>
115 MemoryBuffer::getMemBufferCopy(StringRef InputData, const Twine &BufferName) {
116   std::unique_ptr<MemoryBuffer> Buf =
117       getNewUninitMemBuffer(InputData.size(), BufferName);
118   if (!Buf)
119     return nullptr;
120   memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
121          InputData.size());
122   return Buf;
123 }
124
125 std::unique_ptr<MemoryBuffer>
126 MemoryBuffer::getNewUninitMemBuffer(size_t Size, const Twine &BufferName) {
127   // Allocate space for the MemoryBuffer, the data and the name. It is important
128   // that MemoryBuffer and data are aligned so PointerIntPair works with them.
129   // TODO: Is 16-byte alignment enough?  We copy small object files with large
130   // alignment expectations into this buffer.
131   SmallString<256> NameBuf;
132   StringRef NameRef = BufferName.toStringRef(NameBuf);
133   size_t AlignedStringLen =
134       RoundUpToAlignment(sizeof(MemoryBufferMem) + NameRef.size() + 1, 16);
135   size_t RealLen = AlignedStringLen + Size + 1;
136   char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
137   if (!Mem)
138     return nullptr;
139
140   // The name is stored after the class itself.
141   CopyStringRef(Mem + sizeof(MemoryBufferMem), NameRef);
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   auto *Ret = new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
148   return std::unique_ptr<MemoryBuffer>(Ret);
149 }
150
151 std::unique_ptr<MemoryBuffer>
152 MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
153   std::unique_ptr<MemoryBuffer> SB = getNewUninitMemBuffer(Size, BufferName);
154   if (!SB)
155     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(const Twine &Filename, int64_t FileSize) {
162   SmallString<256> NameBuf;
163   StringRef NameRef = Filename.toStringRef(NameBuf);
164
165   if (NameRef == "-")
166     return getSTDIN();
167   return getFile(Filename, FileSize);
168 }
169
170
171 //===----------------------------------------------------------------------===//
172 // MemoryBuffer::getFile implementation.
173 //===----------------------------------------------------------------------===//
174
175 namespace {
176 /// \brief Memory maps a file descriptor using sys::fs::mapped_file_region.
177 ///
178 /// This handles converting the offset into a legal offset on the platform.
179 class MemoryBufferMMapFile : public MemoryBuffer {
180   sys::fs::mapped_file_region MFR;
181
182   static uint64_t getLegalMapOffset(uint64_t Offset) {
183     return Offset & ~(sys::fs::mapped_file_region::alignment() - 1);
184   }
185
186   static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) {
187     return Len + (Offset - getLegalMapOffset(Offset));
188   }
189
190   const char *getStart(uint64_t Len, uint64_t Offset) {
191     return MFR.const_data() + (Offset - getLegalMapOffset(Offset));
192   }
193
194 public:
195   MemoryBufferMMapFile(bool RequiresNullTerminator, int FD, uint64_t Len,
196                        uint64_t Offset, std::error_code EC)
197       : MFR(FD, false, sys::fs::mapped_file_region::readonly,
198             getLegalMapSize(Len, Offset), getLegalMapOffset(Offset), EC) {
199     if (!EC) {
200       const char *Start = getStart(Len, Offset);
201       init(Start, Start + Len, RequiresNullTerminator);
202     }
203   }
204
205   const char *getBufferIdentifier() const override {
206     // The name is stored after the class itself.
207     return reinterpret_cast<const char *>(this + 1);
208   }
209
210   BufferKind getBufferKind() const override {
211     return MemoryBuffer_MMap;
212   }
213 };
214 }
215
216 static ErrorOr<std::unique_ptr<MemoryBuffer>>
217 getMemoryBufferForStream(int FD, const Twine &BufferName) {
218   const ssize_t ChunkSize = 4096*4;
219   SmallString<ChunkSize> Buffer;
220   ssize_t ReadBytes;
221   // Read into Buffer until we hit EOF.
222   do {
223     Buffer.reserve(Buffer.size() + ChunkSize);
224     ReadBytes = read(FD, Buffer.end(), ChunkSize);
225     if (ReadBytes == -1) {
226       if (errno == EINTR) continue;
227       return std::error_code(errno, std::generic_category());
228     }
229     Buffer.set_size(Buffer.size() + ReadBytes);
230   } while (ReadBytes != 0);
231
232   return MemoryBuffer::getMemBufferCopy(Buffer, BufferName);
233 }
234
235 static ErrorOr<std::unique_ptr<MemoryBuffer>>
236 getFileAux(const Twine &Filename, int64_t FileSize, bool RequiresNullTerminator,
237            bool IsVolatileSize);
238
239 ErrorOr<std::unique_ptr<MemoryBuffer>>
240 MemoryBuffer::getFile(const Twine &Filename, int64_t FileSize,
241                       bool RequiresNullTerminator, bool IsVolatileSize) {
242   return getFileAux(Filename, FileSize, RequiresNullTerminator,
243                     IsVolatileSize);
244 }
245
246 static ErrorOr<std::unique_ptr<MemoryBuffer>>
247 getOpenFileImpl(int FD, const Twine &Filename, uint64_t FileSize,
248                 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
249                 bool IsVolatileSize);
250
251 static ErrorOr<std::unique_ptr<MemoryBuffer>>
252 getFileAux(const Twine &Filename, int64_t FileSize, bool RequiresNullTerminator,
253            bool IsVolatileSize) {
254   int FD;
255   std::error_code EC = sys::fs::openFileForRead(Filename, FD);
256   if (EC)
257     return EC;
258
259   ErrorOr<std::unique_ptr<MemoryBuffer>> Ret =
260       getOpenFileImpl(FD, Filename, FileSize, FileSize, 0,
261                       RequiresNullTerminator, IsVolatileSize);
262   close(FD);
263   return Ret;
264 }
265
266 static bool shouldUseMmap(int FD,
267                           size_t FileSize,
268                           size_t MapSize,
269                           off_t Offset,
270                           bool RequiresNullTerminator,
271                           int PageSize,
272                           bool IsVolatileSize) {
273   // mmap may leave the buffer without null terminator if the file size changed
274   // by the time the last page is mapped in, so avoid it if the file size is
275   // likely to change.
276   if (IsVolatileSize)
277     return false;
278
279   // We don't use mmap for small files because this can severely fragment our
280   // address space.
281   if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize)
282     return false;
283
284   if (!RequiresNullTerminator)
285     return true;
286
287
288   // If we don't know the file size, use fstat to find out.  fstat on an open
289   // file descriptor is cheaper than stat on a random path.
290   // FIXME: this chunk of code is duplicated, but it avoids a fstat when
291   // RequiresNullTerminator = false and MapSize != -1.
292   if (FileSize == size_t(-1)) {
293     sys::fs::file_status Status;
294     if (sys::fs::status(FD, Status))
295       return false;
296     FileSize = Status.getSize();
297   }
298
299   // If we need a null terminator and the end of the map is inside the file,
300   // we cannot use mmap.
301   size_t End = Offset + MapSize;
302   assert(End <= FileSize);
303   if (End != FileSize)
304     return false;
305
306   // Don't try to map files that are exactly a multiple of the system page size
307   // if we need a null terminator.
308   if ((FileSize & (PageSize -1)) == 0)
309     return false;
310
311 #if defined(__CYGWIN__)
312   // Don't try to map files that are exactly a multiple of the physical page size
313   // if we need a null terminator.
314   // FIXME: We should reorganize again getPageSize() on Win32.
315   if ((FileSize & (4096 - 1)) == 0)
316     return false;
317 #endif
318
319   return true;
320 }
321
322 static ErrorOr<std::unique_ptr<MemoryBuffer>>
323 getOpenFileImpl(int FD, const Twine &Filename, uint64_t FileSize,
324                 uint64_t MapSize, int64_t Offset, bool RequiresNullTerminator,
325                 bool IsVolatileSize) {
326   static int PageSize = sys::process::get_self()->page_size();
327
328   // Default is to map the full file.
329   if (MapSize == uint64_t(-1)) {
330     // If we don't know the file size, use fstat to find out.  fstat on an open
331     // file descriptor is cheaper than stat on a random path.
332     if (FileSize == uint64_t(-1)) {
333       sys::fs::file_status Status;
334       std::error_code EC = sys::fs::status(FD, Status);
335       if (EC)
336         return EC;
337
338       // If this not a file or a block device (e.g. it's a named pipe
339       // or character device), we can't trust the size. Create the memory
340       // buffer by copying off the stream.
341       sys::fs::file_type Type = Status.type();
342       if (Type != sys::fs::file_type::regular_file &&
343           Type != sys::fs::file_type::block_file)
344         return getMemoryBufferForStream(FD, Filename);
345
346       FileSize = Status.getSize();
347     }
348     MapSize = FileSize;
349   }
350
351   if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
352                     PageSize, IsVolatileSize)) {
353     std::error_code EC;
354     std::unique_ptr<MemoryBuffer> Result(
355         new (NamedBufferAlloc(Filename))
356         MemoryBufferMMapFile(RequiresNullTerminator, FD, MapSize, Offset, EC));
357     if (!EC)
358       return std::move(Result);
359   }
360
361   std::unique_ptr<MemoryBuffer> Buf =
362       MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
363   if (!Buf) {
364     // Failed to create a buffer. The only way it can fail is if
365     // new(std::nothrow) returns 0.
366     return make_error_code(errc::not_enough_memory);
367   }
368
369   char *BufPtr = const_cast<char *>(Buf->getBufferStart());
370
371   size_t BytesLeft = MapSize;
372 #ifndef HAVE_PREAD
373   if (lseek(FD, Offset, SEEK_SET) == -1)
374     return std::error_code(errno, std::generic_category());
375 #endif
376
377   while (BytesLeft) {
378 #ifdef HAVE_PREAD
379     ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset);
380 #else
381     ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
382 #endif
383     if (NumRead == -1) {
384       if (errno == EINTR)
385         continue;
386       // Error while reading.
387       return std::error_code(errno, std::generic_category());
388     }
389     if (NumRead == 0) {
390       memset(BufPtr, 0, BytesLeft); // zero-initialize rest of the buffer.
391       break;
392     }
393     BytesLeft -= NumRead;
394     BufPtr += NumRead;
395   }
396
397   return std::move(Buf);
398 }
399
400 ErrorOr<std::unique_ptr<MemoryBuffer>>
401 MemoryBuffer::getOpenFile(int FD, const Twine &Filename, uint64_t FileSize,
402                           bool RequiresNullTerminator, bool IsVolatileSize) {
403   return getOpenFileImpl(FD, Filename, FileSize, FileSize, 0,
404                          RequiresNullTerminator, IsVolatileSize);
405 }
406
407 ErrorOr<std::unique_ptr<MemoryBuffer>>
408 MemoryBuffer::getOpenFileSlice(int FD, const Twine &Filename, uint64_t MapSize,
409                                int64_t Offset) {
410   assert(MapSize != uint64_t(-1));
411   return getOpenFileImpl(FD, Filename, -1, MapSize, Offset, false,
412                          /*IsVolatileSize*/ false);
413 }
414
415 ErrorOr<std::unique_ptr<MemoryBuffer>> MemoryBuffer::getSTDIN() {
416   // Read in all of the data from stdin, we cannot mmap stdin.
417   //
418   // FIXME: That isn't necessarily true, we should try to mmap stdin and
419   // fallback if it fails.
420   sys::ChangeStdinToBinary();
421
422   return getMemoryBufferForStream(0, "<stdin>");
423 }
424
425 MemoryBufferRef MemoryBuffer::getMemBufferRef() const {
426   StringRef Data = getBuffer();
427   StringRef Identifier = getBufferIdentifier();
428   return MemoryBufferRef(Data, Identifier);
429 }