Support: Inject LLVM_VERSION_INFO into the Support library
[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 /// 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 std::error_code
161 MemoryBuffer::getFileOrSTDIN(StringRef Filename,
162                              std::unique_ptr<MemoryBuffer> &Result,
163                              int64_t FileSize) {
164   if (Filename == "-")
165     return getSTDIN(Result);
166   return getFile(Filename, Result, FileSize);
167 }
168
169
170 //===----------------------------------------------------------------------===//
171 // MemoryBuffer::getFile implementation.
172 //===----------------------------------------------------------------------===//
173
174 namespace {
175 /// \brief Memory maps a file descriptor using sys::fs::mapped_file_region.
176 ///
177 /// This handles converting the offset into a legal offset on the platform.
178 class MemoryBufferMMapFile : public MemoryBuffer {
179   sys::fs::mapped_file_region MFR;
180
181   static uint64_t getLegalMapOffset(uint64_t Offset) {
182     return Offset & ~(sys::fs::mapped_file_region::alignment() - 1);
183   }
184
185   static uint64_t getLegalMapSize(uint64_t Len, uint64_t Offset) {
186     return Len + (Offset - getLegalMapOffset(Offset));
187   }
188
189   const char *getStart(uint64_t Len, uint64_t Offset) {
190     return MFR.const_data() + (Offset - getLegalMapOffset(Offset));
191   }
192
193 public:
194   MemoryBufferMMapFile(bool RequiresNullTerminator, int FD, uint64_t Len,
195                        uint64_t Offset, std::error_code EC)
196       : MFR(FD, false, sys::fs::mapped_file_region::readonly,
197             getLegalMapSize(Len, Offset), getLegalMapOffset(Offset), EC) {
198     if (!EC) {
199       const char *Start = getStart(Len, Offset);
200       init(Start, Start + Len, RequiresNullTerminator);
201     }
202   }
203
204   const char *getBufferIdentifier() const override {
205     // The name is stored after the class itself.
206     return reinterpret_cast<const char *>(this + 1);
207   }
208
209   BufferKind getBufferKind() const override {
210     return MemoryBuffer_MMap;
211   }
212 };
213 }
214
215 static std::error_code
216 getMemoryBufferForStream(int FD, StringRef BufferName,
217                          std::unique_ptr<MemoryBuffer> &Result) {
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   Result.reset(MemoryBuffer::getMemBufferCopy(Buffer, BufferName));
233   return std::error_code();
234 }
235
236 static std::error_code getFileAux(const char *Filename,
237                                   std::unique_ptr<MemoryBuffer> &Result,
238                                   int64_t FileSize, bool RequiresNullTerminator,
239                                   bool IsVolatileSize);
240
241 std::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 std::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,
257                                        bool RequiresNullTerminator,
258                                        bool IsVolatileSize);
259
260 static std::error_code getFileAux(const char *Filename,
261                                   std::unique_ptr<MemoryBuffer> &Result,
262                                   int64_t FileSize, bool RequiresNullTerminator,
263                                   bool IsVolatileSize) {
264   int FD;
265   std::error_code EC = sys::fs::openFileForRead(Filename, FD);
266   if (EC)
267     return EC;
268
269   std::error_code ret =
270       getOpenFileImpl(FD, Filename, Result, FileSize, FileSize, 0,
271                       RequiresNullTerminator, IsVolatileSize);
272   close(FD);
273   return ret;
274 }
275
276 static bool shouldUseMmap(int FD,
277                           size_t FileSize,
278                           size_t MapSize,
279                           off_t Offset,
280                           bool RequiresNullTerminator,
281                           int PageSize,
282                           bool IsVolatileSize) {
283   // mmap may leave the buffer without null terminator if the file size changed
284   // by the time the last page is mapped in, so avoid it if the file size is
285   // likely to change.
286   if (IsVolatileSize)
287     return false;
288
289   // We don't use mmap for small files because this can severely fragment our
290   // address space.
291   if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize)
292     return false;
293
294   if (!RequiresNullTerminator)
295     return true;
296
297
298   // If we don't know the file size, use fstat to find out.  fstat on an open
299   // file descriptor is cheaper than stat on a random path.
300   // FIXME: this chunk of code is duplicated, but it avoids a fstat when
301   // RequiresNullTerminator = false and MapSize != -1.
302   if (FileSize == size_t(-1)) {
303     sys::fs::file_status Status;
304     if (sys::fs::status(FD, Status))
305       return false;
306     FileSize = Status.getSize();
307   }
308
309   // If we need a null terminator and the end of the map is inside the file,
310   // we cannot use mmap.
311   size_t End = Offset + MapSize;
312   assert(End <= FileSize);
313   if (End != FileSize)
314     return false;
315
316   // Don't try to map files that are exactly a multiple of the system page size
317   // if we need a null terminator.
318   if ((FileSize & (PageSize -1)) == 0)
319     return false;
320
321   return true;
322 }
323
324 static std::error_code getOpenFileImpl(int FD, const char *Filename,
325                                        std::unique_ptr<MemoryBuffer> &Result,
326                                        uint64_t FileSize, uint64_t MapSize,
327                                        int64_t Offset,
328                                        bool RequiresNullTerminator,
329                                        bool IsVolatileSize) {
330   static int PageSize = sys::process::get_self()->page_size();
331
332   // Default is to map the full file.
333   if (MapSize == uint64_t(-1)) {
334     // If we don't know the file size, use fstat to find out.  fstat on an open
335     // file descriptor is cheaper than stat on a random path.
336     if (FileSize == uint64_t(-1)) {
337       sys::fs::file_status Status;
338       std::error_code EC = sys::fs::status(FD, Status);
339       if (EC)
340         return EC;
341
342       // If this not a file or a block device (e.g. it's a named pipe
343       // or character device), we can't trust the size. Create the memory
344       // buffer by copying off the stream.
345       sys::fs::file_type Type = Status.type();
346       if (Type != sys::fs::file_type::regular_file &&
347           Type != sys::fs::file_type::block_file)
348         return getMemoryBufferForStream(FD, Filename, Result);
349
350       FileSize = Status.getSize();
351     }
352     MapSize = FileSize;
353   }
354
355   if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
356                     PageSize, IsVolatileSize)) {
357     std::error_code EC;
358     Result.reset(new (NamedBufferAlloc(Filename)) MemoryBufferMMapFile(
359         RequiresNullTerminator, FD, MapSize, Offset, EC));
360     if (!EC)
361       return std::error_code();
362   }
363
364   MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
365   if (!Buf) {
366     // Failed to create a buffer. The only way it can fail is if
367     // new(std::nothrow) returns 0.
368     return make_error_code(errc::not_enough_memory);
369   }
370
371   std::unique_ptr<MemoryBuffer> SB(Buf);
372   char *BufPtr = const_cast<char*>(SB->getBufferStart());
373
374   size_t BytesLeft = MapSize;
375 #ifndef HAVE_PREAD
376   if (lseek(FD, Offset, SEEK_SET) == -1)
377     return std::error_code(errno, std::generic_category());
378 #endif
379
380   while (BytesLeft) {
381 #ifdef HAVE_PREAD
382     ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset);
383 #else
384     ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
385 #endif
386     if (NumRead == -1) {
387       if (errno == EINTR)
388         continue;
389       // Error while reading.
390       return std::error_code(errno, std::generic_category());
391     }
392     if (NumRead == 0) {
393       memset(BufPtr, 0, BytesLeft); // zero-initialize rest of the buffer.
394       break;
395     }
396     BytesLeft -= NumRead;
397     BufPtr += NumRead;
398   }
399
400   Result.swap(SB);
401   return std::error_code();
402 }
403
404 std::error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
405                                           std::unique_ptr<MemoryBuffer> &Result,
406                                           uint64_t FileSize,
407                                           bool RequiresNullTerminator,
408                                           bool IsVolatileSize) {
409   return getOpenFileImpl(FD, Filename, Result, FileSize, FileSize, 0,
410                          RequiresNullTerminator, IsVolatileSize);
411 }
412
413 std::error_code MemoryBuffer::getOpenFileSlice(
414     int FD, const char *Filename, std::unique_ptr<MemoryBuffer> &Result,
415     uint64_t MapSize, int64_t Offset, bool IsVolatileSize) {
416   return getOpenFileImpl(FD, Filename, Result, -1, MapSize, Offset, false,
417                          IsVolatileSize);
418 }
419
420 //===----------------------------------------------------------------------===//
421 // MemoryBuffer::getSTDIN implementation.
422 //===----------------------------------------------------------------------===//
423
424 std::error_code MemoryBuffer::getSTDIN(std::unique_ptr<MemoryBuffer> &Result) {
425   // Read in all of the data from stdin, we cannot mmap stdin.
426   //
427   // FIXME: That isn't necessarily true, we should try to mmap stdin and
428   // fallback if it fails.
429   sys::ChangeStdinToBinary();
430
431   return getMemoryBufferForStream(0, "<stdin>", Result);
432 }