c395ce72b8d3461464d7d900e18ee064693378de
[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/Errno.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/MathExtras.h"
20 #include "llvm/Support/Path.h"
21 #include "llvm/Support/Process.h"
22 #include "llvm/Support/Program.h"
23 #include <cassert>
24 #include <cerrno>
25 #include <cstdio>
26 #include <cstring>
27 #include <new>
28 #include <sys/types.h>
29 #include <system_error>
30 #if !defined(_MSC_VER) && !defined(__MINGW32__)
31 #include <unistd.h>
32 #else
33 #include <io.h>
34 #endif
35 using namespace llvm;
36 using std::error_code;
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
169 //===----------------------------------------------------------------------===//
170 // MemoryBuffer::getFile implementation.
171 //===----------------------------------------------------------------------===//
172
173 namespace {
174 /// \brief Memory maps a file descriptor using sys::fs::mapped_file_region.
175 ///
176 /// This handles converting the offset into a legal offset on the platform.
177 class MemoryBufferMMapFile : public MemoryBuffer {
178   sys::fs::mapped_file_region MFR;
179
180   static uint64_t getLegalMapOffset(uint64_t Offset) {
181     return Offset & ~(sys::fs::mapped_file_region::alignment() - 1);
182   }
183
184   static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) {
185     return Len + (Offset - getLegalMapOffset(Offset));
186   }
187
188   const char *getStart(uint64_t Len, uint64_t Offset) {
189     return MFR.const_data() + (Offset - getLegalMapOffset(Offset));
190   }
191
192 public:
193   MemoryBufferMMapFile(bool RequiresNullTerminator, int FD, uint64_t Len,
194                        uint64_t Offset, error_code EC)
195       : MFR(FD, false, sys::fs::mapped_file_region::readonly,
196             getLegalMapSize(Len, Offset), getLegalMapOffset(Offset), EC) {
197     if (!EC) {
198       const char *Start = getStart(Len, Offset);
199       init(Start, Start + Len, RequiresNullTerminator);
200     }
201   }
202
203   const char *getBufferIdentifier() const override {
204     // The name is stored after the class itself.
205     return reinterpret_cast<const char *>(this + 1);
206   }
207
208   BufferKind getBufferKind() const override {
209     return MemoryBuffer_MMap;
210   }
211 };
212 }
213
214 static error_code getMemoryBufferForStream(int FD,
215                                            StringRef BufferName,
216                                            std::unique_ptr<MemoryBuffer> &Result) {
217   const ssize_t ChunkSize = 4096*4;
218   SmallString<ChunkSize> Buffer;
219   ssize_t ReadBytes;
220   // Read into Buffer until we hit EOF.
221   do {
222     Buffer.reserve(Buffer.size() + ChunkSize);
223     ReadBytes = read(FD, Buffer.end(), ChunkSize);
224     if (ReadBytes == -1) {
225       if (errno == EINTR) continue;
226       return error_code(errno, std::generic_category());
227     }
228     Buffer.set_size(Buffer.size() + ReadBytes);
229   } while (ReadBytes != 0);
230
231   Result.reset(MemoryBuffer::getMemBufferCopy(Buffer, BufferName));
232   return error_code();
233 }
234
235 static error_code getFileAux(const char *Filename,
236                              std::unique_ptr<MemoryBuffer> &Result,
237                              int64_t FileSize,
238                              bool RequiresNullTerminator,
239                              bool IsVolatileSize);
240
241 error_code MemoryBuffer::getFile(Twine Filename,
242                                  std::unique_ptr<MemoryBuffer> &Result,
243                                  int64_t FileSize,
244                                  bool RequiresNullTerminator,
245                                  bool IsVolatileSize) {
246   // Ensure the path is null terminated.
247   SmallString<256> PathBuf;
248   StringRef NullTerminatedName = Filename.toNullTerminatedStringRef(PathBuf);
249   return getFileAux(NullTerminatedName.data(), Result, FileSize,
250                     RequiresNullTerminator, IsVolatileSize);
251 }
252
253 static error_code getOpenFileImpl(int FD, const char *Filename,
254                                   std::unique_ptr<MemoryBuffer> &Result,
255                                   uint64_t FileSize, uint64_t MapSize,
256                                   int64_t Offset, bool RequiresNullTerminator,
257                                   bool IsVolatileSize);
258
259 static error_code getFileAux(const char *Filename,
260                              std::unique_ptr<MemoryBuffer> &Result, int64_t FileSize,
261                              bool RequiresNullTerminator,
262                              bool IsVolatileSize) {
263   int FD;
264   error_code EC = sys::fs::openFileForRead(Filename, FD);
265   if (EC)
266     return EC;
267
268   error_code ret = getOpenFileImpl(FD, Filename, Result, FileSize, FileSize, 0,
269                                    RequiresNullTerminator, IsVolatileSize);
270   close(FD);
271   return ret;
272 }
273
274 static bool shouldUseMmap(int FD,
275                           size_t FileSize,
276                           size_t MapSize,
277                           off_t Offset,
278                           bool RequiresNullTerminator,
279                           int PageSize,
280                           bool IsVolatileSize) {
281   // mmap may leave the buffer without null terminator if the file size changed
282   // by the time the last page is mapped in, so avoid it if the file size is
283   // likely to change.
284   if (IsVolatileSize)
285     return false;
286
287   // We don't use mmap for small files because this can severely fragment our
288   // address space.
289   if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize)
290     return false;
291
292   if (!RequiresNullTerminator)
293     return true;
294
295
296   // If we don't know the file size, use fstat to find out.  fstat on an open
297   // file descriptor is cheaper than stat on a random path.
298   // FIXME: this chunk of code is duplicated, but it avoids a fstat when
299   // RequiresNullTerminator = false and MapSize != -1.
300   if (FileSize == size_t(-1)) {
301     sys::fs::file_status Status;
302     if (sys::fs::status(FD, Status))
303       return false;
304     FileSize = Status.getSize();
305   }
306
307   // If we need a null terminator and the end of the map is inside the file,
308   // we cannot use mmap.
309   size_t End = Offset + MapSize;
310   assert(End <= FileSize);
311   if (End != FileSize)
312     return false;
313
314   // Don't try to map files that are exactly a multiple of the system page size
315   // if we need a null terminator.
316   if ((FileSize & (PageSize -1)) == 0)
317     return false;
318
319   return true;
320 }
321
322 static error_code getOpenFileImpl(int FD, const char *Filename,
323                                   std::unique_ptr<MemoryBuffer> &Result,
324                                   uint64_t FileSize, uint64_t MapSize,
325                                   int64_t Offset, bool RequiresNullTerminator,
326                                   bool IsVolatileSize) {
327   static int PageSize = sys::process::get_self()->page_size();
328
329   // Default is to map the full file.
330   if (MapSize == uint64_t(-1)) {
331     // If we don't know the file size, use fstat to find out.  fstat on an open
332     // file descriptor is cheaper than stat on a random path.
333     if (FileSize == uint64_t(-1)) {
334       sys::fs::file_status Status;
335       error_code EC = sys::fs::status(FD, Status);
336       if (EC)
337         return EC;
338
339       // If this not a file or a block device (e.g. it's a named pipe
340       // or character device), we can't trust the size. Create the memory
341       // buffer by copying off the stream.
342       sys::fs::file_type Type = Status.type();
343       if (Type != sys::fs::file_type::regular_file &&
344           Type != sys::fs::file_type::block_file)
345         return getMemoryBufferForStream(FD, Filename, Result);
346
347       FileSize = Status.getSize();
348     }
349     MapSize = FileSize;
350   }
351
352   if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
353                     PageSize, IsVolatileSize)) {
354     error_code EC;
355     Result.reset(new (NamedBufferAlloc(Filename)) MemoryBufferMMapFile(
356         RequiresNullTerminator, FD, MapSize, Offset, EC));
357     if (!EC)
358       return error_code();
359   }
360
361   MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
362   if (!Buf) {
363     // Failed to create a buffer. The only way it can fail is if
364     // new(std::nothrow) returns 0.
365     return std::make_error_code(std::errc::not_enough_memory);
366   }
367
368   std::unique_ptr<MemoryBuffer> SB(Buf);
369   char *BufPtr = const_cast<char*>(SB->getBufferStart());
370
371   size_t BytesLeft = MapSize;
372 #ifndef HAVE_PREAD
373   if (lseek(FD, Offset, SEEK_SET) == -1)
374     return 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 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   Result.swap(SB);
398   return error_code();
399 }
400
401 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
402                                      std::unique_ptr<MemoryBuffer> &Result,
403                                      uint64_t FileSize,
404                                      bool RequiresNullTerminator,
405                                      bool IsVolatileSize) {
406   return getOpenFileImpl(FD, Filename, Result, FileSize, FileSize, 0,
407                          RequiresNullTerminator, IsVolatileSize);
408 }
409
410 error_code MemoryBuffer::getOpenFileSlice(int FD, const char *Filename,
411                                           std::unique_ptr<MemoryBuffer> &Result,
412                                           uint64_t MapSize, int64_t Offset,
413                                           bool IsVolatileSize) {
414   return getOpenFileImpl(FD, Filename, Result, -1, MapSize, Offset, false,
415                          IsVolatileSize);
416 }
417
418 //===----------------------------------------------------------------------===//
419 // MemoryBuffer::getSTDIN implementation.
420 //===----------------------------------------------------------------------===//
421
422 error_code MemoryBuffer::getSTDIN(std::unique_ptr<MemoryBuffer> &Result) {
423   // Read in all of the data from stdin, we cannot mmap stdin.
424   //
425   // FIXME: That isn't necessarily true, we should try to mmap stdin and
426   // fallback if it fails.
427   sys::ChangeStdinToBinary();
428
429   return getMemoryBufferForStream(0, "<stdin>", Result);
430 }