Fix build on windows.
[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
37 //===----------------------------------------------------------------------===//
38 // MemoryBuffer implementation itself.
39 //===----------------------------------------------------------------------===//
40
41 MemoryBuffer::~MemoryBuffer() { }
42
43 /// init - Initialize this MemoryBuffer as a reference to externally allocated
44 /// memory, memory that we know is already null terminated.
45 void MemoryBuffer::init(const char *BufStart, const char *BufEnd,
46                         bool RequiresNullTerminator) {
47   assert((!RequiresNullTerminator || BufEnd[0] == 0) &&
48          "Buffer is not null terminated!");
49   BufferStart = BufStart;
50   BufferEnd = BufEnd;
51 }
52
53 //===----------------------------------------------------------------------===//
54 // MemoryBufferMem implementation.
55 //===----------------------------------------------------------------------===//
56
57 /// CopyStringRef - Copies contents of a StringRef into a block of memory and
58 /// null-terminates it.
59 static void CopyStringRef(char *Memory, StringRef Data) {
60   memcpy(Memory, Data.data(), Data.size());
61   Memory[Data.size()] = 0; // Null terminate string.
62 }
63
64 namespace {
65 struct NamedBufferAlloc {
66   StringRef Name;
67   NamedBufferAlloc(StringRef Name) : Name(Name) {}
68 };
69 }
70
71 void *operator new(size_t N, const NamedBufferAlloc &Alloc) {
72   char *Mem = static_cast<char *>(operator new(N + Alloc.Name.size() + 1));
73   CopyStringRef(Mem + N, Alloc.Name);
74   return Mem;
75 }
76
77 namespace {
78 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
79 class MemoryBufferMem : public MemoryBuffer {
80 public:
81   MemoryBufferMem(StringRef InputData, bool RequiresNullTerminator) {
82     init(InputData.begin(), InputData.end(), RequiresNullTerminator);
83   }
84
85   const char *getBufferIdentifier() const override {
86      // The name is stored after the class itself.
87     return reinterpret_cast<const char*>(this + 1);
88   }
89
90   BufferKind getBufferKind() const override {
91     return MemoryBuffer_Malloc;
92   }
93 };
94 }
95
96 /// getMemBuffer - Open the specified memory range as a MemoryBuffer.  Note
97 /// that InputData must be a null terminated if RequiresNullTerminator is true!
98 MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
99                                          StringRef BufferName,
100                                          bool RequiresNullTerminator) {
101   return new (NamedBufferAlloc(BufferName))
102       MemoryBufferMem(InputData, RequiresNullTerminator);
103 }
104
105 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
106 /// copying the contents and taking ownership of it.  This has no requirements
107 /// on EndPtr[0].
108 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
109                                              StringRef BufferName) {
110   MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
111   if (!Buf) return nullptr;
112   memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
113          InputData.size());
114   return Buf;
115 }
116
117 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
118 /// that is not initialized.  Note that the caller should initialize the
119 /// memory allocated by this method.  The memory is owned by the MemoryBuffer
120 /// object.
121 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
122                                                   StringRef BufferName) {
123   // Allocate space for the MemoryBuffer, the data and the name. It is important
124   // that MemoryBuffer and data are aligned so PointerIntPair works with them.
125   // TODO: Is 16-byte alignment enough?  We copy small object files with large
126   // alignment expectations into this buffer.
127   size_t AlignedStringLen =
128       RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1, 16);
129   size_t RealLen = AlignedStringLen + Size + 1;
130   char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
131   if (!Mem) return nullptr;
132
133   // The name is stored after the class itself.
134   CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
135
136   // The buffer begins after the name and must be aligned.
137   char *Buf = Mem + AlignedStringLen;
138   Buf[Size] = 0; // Null terminate buffer.
139
140   return new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
141 }
142
143 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
144 /// is completely initialized to zeros.  Note that the caller should
145 /// initialize the memory allocated by this method.  The memory is owned by
146 /// the MemoryBuffer object.
147 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
148   MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
149   if (!SB) return nullptr;
150   memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
151   return SB;
152 }
153
154
155 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
156 /// if the Filename is "-".  If an error occurs, this returns null and fills
157 /// in *ErrStr with a reason.  If stdin is empty, this API (unlike getSTDIN)
158 /// returns an empty buffer.
159 std::error_code
160 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, std::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 std::error_code
215 getMemoryBufferForStream(int FD, 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 std::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 std::error_code();
233 }
234
235 static std::error_code getFileAux(const char *Filename,
236                                   std::unique_ptr<MemoryBuffer> &Result,
237                                   int64_t FileSize, bool RequiresNullTerminator,
238                                   bool IsVolatileSize);
239
240 std::error_code MemoryBuffer::getFile(Twine Filename,
241                                       std::unique_ptr<MemoryBuffer> &Result,
242                                       int64_t FileSize,
243                                       bool RequiresNullTerminator,
244                                       bool IsVolatileSize) {
245   // Ensure the path is null terminated.
246   SmallString<256> PathBuf;
247   StringRef NullTerminatedName = Filename.toNullTerminatedStringRef(PathBuf);
248   return getFileAux(NullTerminatedName.data(), Result, FileSize,
249                     RequiresNullTerminator, IsVolatileSize);
250 }
251
252 static std::error_code getOpenFileImpl(int FD, const char *Filename,
253                                        std::unique_ptr<MemoryBuffer> &Result,
254                                        uint64_t FileSize, uint64_t MapSize,
255                                        int64_t Offset,
256                                        bool RequiresNullTerminator,
257                                        bool IsVolatileSize);
258
259 static std::error_code getFileAux(const char *Filename,
260                                   std::unique_ptr<MemoryBuffer> &Result,
261                                   int64_t FileSize, bool RequiresNullTerminator,
262                                   bool IsVolatileSize) {
263   int FD;
264   std::error_code EC = sys::fs::openFileForRead(Filename, FD);
265   if (EC)
266     return EC;
267
268   std::error_code ret =
269       getOpenFileImpl(FD, Filename, Result, FileSize, FileSize, 0,
270                       RequiresNullTerminator, IsVolatileSize);
271   close(FD);
272   return ret;
273 }
274
275 static bool shouldUseMmap(int FD,
276                           size_t FileSize,
277                           size_t MapSize,
278                           off_t Offset,
279                           bool RequiresNullTerminator,
280                           int PageSize,
281                           bool IsVolatileSize) {
282   // mmap may leave the buffer without null terminator if the file size changed
283   // by the time the last page is mapped in, so avoid it if the file size is
284   // likely to change.
285   if (IsVolatileSize)
286     return false;
287
288   // We don't use mmap for small files because this can severely fragment our
289   // address space.
290   if (MapSize < 4 * 4096 || MapSize < (unsigned)PageSize)
291     return false;
292
293   if (!RequiresNullTerminator)
294     return true;
295
296
297   // If we don't know the file size, use fstat to find out.  fstat on an open
298   // file descriptor is cheaper than stat on a random path.
299   // FIXME: this chunk of code is duplicated, but it avoids a fstat when
300   // RequiresNullTerminator = false and MapSize != -1.
301   if (FileSize == size_t(-1)) {
302     sys::fs::file_status Status;
303     if (sys::fs::status(FD, Status))
304       return false;
305     FileSize = Status.getSize();
306   }
307
308   // If we need a null terminator and the end of the map is inside the file,
309   // we cannot use mmap.
310   size_t End = Offset + MapSize;
311   assert(End <= FileSize);
312   if (End != FileSize)
313     return false;
314
315   // Don't try to map files that are exactly a multiple of the system page size
316   // if we need a null terminator.
317   if ((FileSize & (PageSize -1)) == 0)
318     return false;
319
320   return true;
321 }
322
323 static std::error_code getOpenFileImpl(int FD, const char *Filename,
324                                        std::unique_ptr<MemoryBuffer> &Result,
325                                        uint64_t FileSize, uint64_t MapSize,
326                                        int64_t Offset,
327                                        bool RequiresNullTerminator,
328                                        bool IsVolatileSize) {
329   static int PageSize = sys::process::get_self()->page_size();
330
331   // Default is to map the full file.
332   if (MapSize == uint64_t(-1)) {
333     // If we don't know the file size, use fstat to find out.  fstat on an open
334     // file descriptor is cheaper than stat on a random path.
335     if (FileSize == uint64_t(-1)) {
336       sys::fs::file_status Status;
337       std::error_code EC = sys::fs::status(FD, Status);
338       if (EC)
339         return EC;
340
341       // If this not a file or a block device (e.g. it's a named pipe
342       // or character device), we can't trust the size. Create the memory
343       // buffer by copying off the stream.
344       sys::fs::file_type Type = Status.type();
345       if (Type != sys::fs::file_type::regular_file &&
346           Type != sys::fs::file_type::block_file)
347         return getMemoryBufferForStream(FD, Filename, Result);
348
349       FileSize = Status.getSize();
350     }
351     MapSize = FileSize;
352   }
353
354   if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
355                     PageSize, IsVolatileSize)) {
356     std::error_code EC;
357     Result.reset(new (NamedBufferAlloc(Filename)) MemoryBufferMMapFile(
358         RequiresNullTerminator, FD, MapSize, Offset, EC));
359     if (!EC)
360       return std::error_code();
361   }
362
363   MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
364   if (!Buf) {
365     // Failed to create a buffer. The only way it can fail is if
366     // new(std::nothrow) returns 0.
367     return std::make_error_code(std::errc::not_enough_memory);
368   }
369
370   std::unique_ptr<MemoryBuffer> SB(Buf);
371   char *BufPtr = const_cast<char*>(SB->getBufferStart());
372
373   size_t BytesLeft = MapSize;
374 #ifndef HAVE_PREAD
375   if (lseek(FD, Offset, SEEK_SET) == -1)
376     return std::error_code(errno, std::generic_category());
377 #endif
378
379   while (BytesLeft) {
380 #ifdef HAVE_PREAD
381     ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset);
382 #else
383     ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
384 #endif
385     if (NumRead == -1) {
386       if (errno == EINTR)
387         continue;
388       // Error while reading.
389       return std::error_code(errno, std::generic_category());
390     }
391     if (NumRead == 0) {
392       memset(BufPtr, 0, BytesLeft); // zero-initialize rest of the buffer.
393       break;
394     }
395     BytesLeft -= NumRead;
396     BufPtr += NumRead;
397   }
398
399   Result.swap(SB);
400   return std::error_code();
401 }
402
403 std::error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
404                                           std::unique_ptr<MemoryBuffer> &Result,
405                                           uint64_t FileSize,
406                                           bool RequiresNullTerminator,
407                                           bool IsVolatileSize) {
408   return getOpenFileImpl(FD, Filename, Result, FileSize, FileSize, 0,
409                          RequiresNullTerminator, IsVolatileSize);
410 }
411
412 std::error_code MemoryBuffer::getOpenFileSlice(
413     int FD, const char *Filename, std::unique_ptr<MemoryBuffer> &Result,
414     uint64_t MapSize, int64_t Offset, bool IsVolatileSize) {
415   return getOpenFileImpl(FD, Filename, Result, -1, MapSize, Offset, false,
416                          IsVolatileSize);
417 }
418
419 //===----------------------------------------------------------------------===//
420 // MemoryBuffer::getSTDIN implementation.
421 //===----------------------------------------------------------------------===//
422
423 std::error_code MemoryBuffer::getSTDIN(std::unique_ptr<MemoryBuffer> &Result) {
424   // Read in all of the data from stdin, we cannot mmap stdin.
425   //
426   // FIXME: That isn't necessarily true, we should try to mmap stdin and
427   // fallback if it fails.
428   sys::ChangeStdinToBinary();
429
430   return getMemoryBufferForStream(0, "<stdin>", Result);
431 }