[Support/MemoryBuffer] Remove the assertion that the file size did not shrink.
[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/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"
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
50 MemoryBuffer::~MemoryBuffer() { }
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 {
75   StringRef Name;
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   const char *getBufferIdentifier() const override {
95      // The name is stored after the class itself.
96     return reinterpret_cast<const char*>(this + 1);
97   }
98
99   BufferKind getBufferKind() const 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!
107 MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
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].
117 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
118                                              StringRef BufferName) {
119   MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
120   if (!Buf) return nullptr;
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.
130 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
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   // TODO: Is 16-byte alignment enough?  We copy small object files with large
135   // alignment expectations into this buffer.
136   size_t AlignedStringLen =
137       RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1, 16);
138   size_t RealLen = AlignedStringLen + Size + 1;
139   char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
140   if (!Mem) return nullptr;
141
142   // The name is stored after the class itself.
143   CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
144
145   // The buffer begins after the name and must be aligned.
146   char *Buf = Mem + AlignedStringLen;
147   Buf[Size] = 0; // Null terminate buffer.
148
149   return new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
150 }
151
152 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
153 /// is completely initialized to zeros.  Note that the caller should
154 /// initialize the memory allocated by this method.  The memory is owned by
155 /// the MemoryBuffer object.
156 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
157   MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
158   if (!SB) return nullptr;
159   memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
160   return SB;
161 }
162
163
164 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
165 /// if the Filename is "-".  If an error occurs, this returns null and fills
166 /// in *ErrStr with a reason.  If stdin is empty, this API (unlike getSTDIN)
167 /// returns an empty buffer.
168 error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
169                                         std::unique_ptr<MemoryBuffer> &Result,
170                                         int64_t FileSize) {
171   if (Filename == "-")
172     return getSTDIN(Result);
173   return getFile(Filename, Result, FileSize);
174 }
175
176 error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
177                                         OwningPtr<MemoryBuffer> &Result,
178                                         int64_t FileSize) {
179   std::unique_ptr<MemoryBuffer> MB;
180   error_code ec = getFileOrSTDIN(Filename, MB, FileSize);
181   Result = std::move(MB);
182   return ec;
183 }
184
185
186 //===----------------------------------------------------------------------===//
187 // MemoryBuffer::getFile implementation.
188 //===----------------------------------------------------------------------===//
189
190 namespace {
191 /// \brief Memory maps a file descriptor using sys::fs::mapped_file_region.
192 ///
193 /// This handles converting the offset into a legal offset on the platform.
194 class MemoryBufferMMapFile : public MemoryBuffer {
195   sys::fs::mapped_file_region MFR;
196
197   static uint64_t getLegalMapOffset(uint64_t Offset) {
198     return Offset & ~(sys::fs::mapped_file_region::alignment() - 1);
199   }
200
201   static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) {
202     return Len + (Offset - getLegalMapOffset(Offset));
203   }
204
205   const char *getStart(uint64_t Len, uint64_t Offset) {
206     return MFR.const_data() + (Offset - getLegalMapOffset(Offset));
207   }
208
209 public:
210   MemoryBufferMMapFile(bool RequiresNullTerminator, int FD, uint64_t Len,
211                        uint64_t Offset, error_code EC)
212       : MFR(FD, false, sys::fs::mapped_file_region::readonly,
213             getLegalMapSize(Len, Offset), getLegalMapOffset(Offset), EC) {
214     if (!EC) {
215       const char *Start = getStart(Len, Offset);
216       init(Start, Start + Len, RequiresNullTerminator);
217     }
218   }
219
220   const char *getBufferIdentifier() const override {
221     // The name is stored after the class itself.
222     return reinterpret_cast<const char *>(this + 1);
223   }
224
225   BufferKind getBufferKind() const override {
226     return MemoryBuffer_MMap;
227   }
228 };
229 }
230
231 static error_code getMemoryBufferForStream(int FD,
232                                            StringRef BufferName,
233                                            std::unique_ptr<MemoryBuffer> &Result) {
234   const ssize_t ChunkSize = 4096*4;
235   SmallString<ChunkSize> Buffer;
236   ssize_t ReadBytes;
237   // Read into Buffer until we hit EOF.
238   do {
239     Buffer.reserve(Buffer.size() + ChunkSize);
240     ReadBytes = read(FD, Buffer.end(), ChunkSize);
241     if (ReadBytes == -1) {
242       if (errno == EINTR) continue;
243       return error_code(errno, posix_category());
244     }
245     Buffer.set_size(Buffer.size() + ReadBytes);
246   } while (ReadBytes != 0);
247
248   Result.reset(MemoryBuffer::getMemBufferCopy(Buffer, BufferName));
249   return error_code::success();
250 }
251
252 static error_code getFileAux(const char *Filename,
253                              std::unique_ptr<MemoryBuffer> &Result,
254                              int64_t FileSize,
255                              bool RequiresNullTerminator,
256                              bool IsVolatileSize);
257
258 error_code MemoryBuffer::getFile(Twine Filename,
259                                  std::unique_ptr<MemoryBuffer> &Result,
260                                  int64_t FileSize,
261                                  bool RequiresNullTerminator,
262                                  bool IsVolatileSize) {
263   // Ensure the path is null terminated.
264   SmallString<256> PathBuf;
265   StringRef NullTerminatedName = Filename.toNullTerminatedStringRef(PathBuf);
266   return getFileAux(NullTerminatedName.data(), Result, FileSize,
267                     RequiresNullTerminator, IsVolatileSize);
268 }
269
270 error_code MemoryBuffer::getFile(Twine Filename,
271                                  OwningPtr<MemoryBuffer> &Result,
272                                  int64_t FileSize,
273                                  bool RequiresNullTerminator,
274                                  bool IsVolatileSize) {
275   std::unique_ptr<MemoryBuffer> MB;
276   error_code ec = getFile(Filename, MB, FileSize, RequiresNullTerminator,
277                           IsVolatileSize);
278   Result = std::move(MB);
279   return ec;
280 }
281
282 static error_code getOpenFileImpl(int FD, const char *Filename,
283                                   std::unique_ptr<MemoryBuffer> &Result,
284                                   uint64_t FileSize, uint64_t MapSize,
285                                   int64_t Offset, bool RequiresNullTerminator,
286                                   bool IsVolatileSize);
287
288 static error_code getFileAux(const char *Filename,
289                              std::unique_ptr<MemoryBuffer> &Result, int64_t FileSize,
290                              bool RequiresNullTerminator,
291                              bool IsVolatileSize) {
292   int FD;
293   error_code EC = sys::fs::openFileForRead(Filename, FD);
294   if (EC)
295     return EC;
296
297   error_code ret = getOpenFileImpl(FD, Filename, Result, FileSize, FileSize, 0,
298                                    RequiresNullTerminator, IsVolatileSize);
299   close(FD);
300   return ret;
301 }
302
303 static bool shouldUseMmap(int FD,
304                           size_t FileSize,
305                           size_t MapSize,
306                           off_t Offset,
307                           bool RequiresNullTerminator,
308                           int PageSize,
309                           bool IsVolatileSize) {
310   // mmap may leave the buffer without null terminator if the file size changed
311   // by the time the last page is mapped in, so avoid it if the file size is
312   // likely to change.
313   if (IsVolatileSize)
314     return false;
315
316   // We don't use mmap for small files because this can severely fragment our
317   // address space.
318   if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize)
319     return false;
320
321   if (!RequiresNullTerminator)
322     return true;
323
324
325   // If we don't know the file size, use fstat to find out.  fstat on an open
326   // file descriptor is cheaper than stat on a random path.
327   // FIXME: this chunk of code is duplicated, but it avoids a fstat when
328   // RequiresNullTerminator = false and MapSize != -1.
329   if (FileSize == size_t(-1)) {
330     sys::fs::file_status Status;
331     error_code EC = sys::fs::status(FD, Status);
332     if (EC)
333       return EC;
334     FileSize = Status.getSize();
335   }
336
337   // If we need a null terminator and the end of the map is inside the file,
338   // we cannot use mmap.
339   size_t End = Offset + MapSize;
340   assert(End <= FileSize);
341   if (End != FileSize)
342     return false;
343
344 #if defined(_WIN32) || defined(__CYGWIN__)
345   // Don't peek the next page if file is multiple of *physical* pagesize(4k)
346   // but is not multiple of AllocationGranularity(64k),
347   // when a null terminator is required.
348   // FIXME: It's not good to hardcode 4096 here. dwPageSize shows 4096.
349   if ((FileSize & (4096 - 1)) == 0)
350     return false;
351 #endif
352
353   // Don't try to map files that are exactly a multiple of the system page size
354   // if we need a null terminator.
355   if ((FileSize & (PageSize -1)) == 0)
356     return false;
357
358   return true;
359 }
360
361 static error_code getOpenFileImpl(int FD, const char *Filename,
362                                   std::unique_ptr<MemoryBuffer> &Result,
363                                   uint64_t FileSize, uint64_t MapSize,
364                                   int64_t Offset, bool RequiresNullTerminator,
365                                   bool IsVolatileSize) {
366   static int PageSize = sys::process::get_self()->page_size();
367
368   // Default is to map the full file.
369   if (MapSize == uint64_t(-1)) {
370     // If we don't know the file size, use fstat to find out.  fstat on an open
371     // file descriptor is cheaper than stat on a random path.
372     if (FileSize == uint64_t(-1)) {
373       sys::fs::file_status Status;
374       error_code EC = sys::fs::status(FD, Status);
375       if (EC)
376         return EC;
377
378       // If this not a file or a block device (e.g. it's a named pipe
379       // or character device), we can't trust the size. Create the memory
380       // buffer by copying off the stream.
381       sys::fs::file_type Type = Status.type();
382       if (Type != sys::fs::file_type::regular_file &&
383           Type != sys::fs::file_type::block_file)
384         return getMemoryBufferForStream(FD, Filename, Result);
385
386       FileSize = Status.getSize();
387     }
388     MapSize = FileSize;
389   }
390
391   if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
392                     PageSize, IsVolatileSize)) {
393     error_code EC;
394     Result.reset(new (NamedBufferAlloc(Filename)) MemoryBufferMMapFile(
395         RequiresNullTerminator, FD, MapSize, Offset, EC));
396     if (!EC)
397       return error_code::success();
398   }
399
400   MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
401   if (!Buf) {
402     // Failed to create a buffer. The only way it can fail is if
403     // new(std::nothrow) returns 0.
404     return make_error_code(errc::not_enough_memory);
405   }
406
407   std::unique_ptr<MemoryBuffer> SB(Buf);
408   char *BufPtr = const_cast<char*>(SB->getBufferStart());
409
410   size_t BytesLeft = MapSize;
411 #ifndef HAVE_PREAD
412   if (lseek(FD, Offset, SEEK_SET) == -1)
413     return error_code(errno, posix_category());
414 #endif
415
416   while (BytesLeft) {
417 #ifdef HAVE_PREAD
418     ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset);
419 #else
420     ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
421 #endif
422     if (NumRead == -1) {
423       if (errno == EINTR)
424         continue;
425       // Error while reading.
426       return error_code(errno, posix_category());
427     }
428     if (NumRead == 0) {
429       memset(BufPtr, 0, BytesLeft); // zero-initialize rest of the buffer.
430       break;
431     }
432     BytesLeft -= NumRead;
433     BufPtr += NumRead;
434   }
435
436   Result.swap(SB);
437   return error_code::success();
438 }
439
440 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
441                                      std::unique_ptr<MemoryBuffer> &Result,
442                                      uint64_t FileSize,
443                                      bool RequiresNullTerminator,
444                                      bool IsVolatileSize) {
445   return getOpenFileImpl(FD, Filename, Result, FileSize, FileSize, 0,
446                          RequiresNullTerminator, IsVolatileSize);
447 }
448
449 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
450                                      OwningPtr<MemoryBuffer> &Result,
451                                      uint64_t FileSize,
452                                      bool RequiresNullTerminator,
453                                      bool IsVolatileSize) {
454   std::unique_ptr<MemoryBuffer> MB;
455   error_code ec = getOpenFileImpl(FD, Filename, MB, FileSize, FileSize, 0,
456                                   RequiresNullTerminator, IsVolatileSize);
457   Result = std::move(MB);
458   return ec;
459 }
460
461 error_code MemoryBuffer::getOpenFileSlice(int FD, const char *Filename,
462                                           std::unique_ptr<MemoryBuffer> &Result,
463                                           uint64_t MapSize, int64_t Offset,
464                                           bool IsVolatileSize) {
465   return getOpenFileImpl(FD, Filename, Result, -1, MapSize, Offset, false,
466                          IsVolatileSize);
467 }
468
469 error_code MemoryBuffer::getOpenFileSlice(int FD, const char *Filename,
470                                           OwningPtr<MemoryBuffer> &Result,
471                                           uint64_t MapSize, int64_t Offset,
472                                           bool IsVolatileSize) {
473   std::unique_ptr<MemoryBuffer> MB;
474   error_code ec = getOpenFileImpl(FD, Filename, MB, -1, MapSize, Offset, false,
475                                   IsVolatileSize);
476   Result = std::move(MB);
477   return ec;
478 }
479
480 //===----------------------------------------------------------------------===//
481 // MemoryBuffer::getSTDIN implementation.
482 //===----------------------------------------------------------------------===//
483
484 error_code MemoryBuffer::getSTDIN(std::unique_ptr<MemoryBuffer> &Result) {
485   // Read in all of the data from stdin, we cannot mmap stdin.
486   //
487   // FIXME: That isn't necessarily true, we should try to mmap stdin and
488   // fallback if it fails.
489   sys::ChangeStdinToBinary();
490
491   return getMemoryBufferForStream(0, "<stdin>", Result);
492 }
493
494 error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &Result) {
495   std::unique_ptr<MemoryBuffer> MB;
496   error_code ec = getSTDIN(MB);
497   Result = std::move(MB);
498   return ec;
499 }