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