MemoryBuffer: remove unusued definitions
[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     error_code EC = sys::fs::status(FD, Status);
324     if (EC)
325       return EC;
326     FileSize = Status.getSize();
327   }
328
329   // If we need a null terminator and the end of the map is inside the file,
330   // we cannot use mmap.
331   size_t End = Offset + MapSize;
332   assert(End <= FileSize);
333   if (End != FileSize)
334     return false;
335
336 #if defined(_WIN32) || defined(__CYGWIN__)
337   // Don't peek the next page if file is multiple of *physical* pagesize(4k)
338   // but is not multiple of AllocationGranularity(64k),
339   // when a null terminator is required.
340   // FIXME: It's not good to hardcode 4096 here. dwPageSize shows 4096.
341   if ((FileSize & (4096 - 1)) == 0)
342     return false;
343 #endif
344
345   // Don't try to map files that are exactly a multiple of the system page size
346   // if we need a null terminator.
347   if ((FileSize & (PageSize -1)) == 0)
348     return false;
349
350   return true;
351 }
352
353 static error_code getOpenFileImpl(int FD, const char *Filename,
354                                   std::unique_ptr<MemoryBuffer> &Result,
355                                   uint64_t FileSize, uint64_t MapSize,
356                                   int64_t Offset, bool RequiresNullTerminator,
357                                   bool IsVolatileSize) {
358   static int PageSize = sys::process::get_self()->page_size();
359
360   // Default is to map the full file.
361   if (MapSize == uint64_t(-1)) {
362     // If we don't know the file size, use fstat to find out.  fstat on an open
363     // file descriptor is cheaper than stat on a random path.
364     if (FileSize == uint64_t(-1)) {
365       sys::fs::file_status Status;
366       error_code EC = sys::fs::status(FD, Status);
367       if (EC)
368         return EC;
369
370       // If this not a file or a block device (e.g. it's a named pipe
371       // or character device), we can't trust the size. Create the memory
372       // buffer by copying off the stream.
373       sys::fs::file_type Type = Status.type();
374       if (Type != sys::fs::file_type::regular_file &&
375           Type != sys::fs::file_type::block_file)
376         return getMemoryBufferForStream(FD, Filename, Result);
377
378       FileSize = Status.getSize();
379     }
380     MapSize = FileSize;
381   }
382
383   if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
384                     PageSize, IsVolatileSize)) {
385     error_code EC;
386     Result.reset(new (NamedBufferAlloc(Filename)) MemoryBufferMMapFile(
387         RequiresNullTerminator, FD, MapSize, Offset, EC));
388     if (!EC)
389       return error_code::success();
390   }
391
392   MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
393   if (!Buf) {
394     // Failed to create a buffer. The only way it can fail is if
395     // new(std::nothrow) returns 0.
396     return make_error_code(errc::not_enough_memory);
397   }
398
399   std::unique_ptr<MemoryBuffer> SB(Buf);
400   char *BufPtr = const_cast<char*>(SB->getBufferStart());
401
402   size_t BytesLeft = MapSize;
403 #ifndef HAVE_PREAD
404   if (lseek(FD, Offset, SEEK_SET) == -1)
405     return error_code(errno, posix_category());
406 #endif
407
408   while (BytesLeft) {
409 #ifdef HAVE_PREAD
410     ssize_t NumRead = ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+Offset);
411 #else
412     ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
413 #endif
414     if (NumRead == -1) {
415       if (errno == EINTR)
416         continue;
417       // Error while reading.
418       return error_code(errno, posix_category());
419     }
420     if (NumRead == 0) {
421       memset(BufPtr, 0, BytesLeft); // zero-initialize rest of the buffer.
422       break;
423     }
424     BytesLeft -= NumRead;
425     BufPtr += NumRead;
426   }
427
428   Result.swap(SB);
429   return error_code::success();
430 }
431
432 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
433                                      std::unique_ptr<MemoryBuffer> &Result,
434                                      uint64_t FileSize,
435                                      bool RequiresNullTerminator,
436                                      bool IsVolatileSize) {
437   return getOpenFileImpl(FD, Filename, Result, FileSize, FileSize, 0,
438                          RequiresNullTerminator, IsVolatileSize);
439 }
440
441 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
442                                      OwningPtr<MemoryBuffer> &Result,
443                                      uint64_t FileSize,
444                                      bool RequiresNullTerminator,
445                                      bool IsVolatileSize) {
446   std::unique_ptr<MemoryBuffer> MB;
447   error_code ec = getOpenFileImpl(FD, Filename, MB, FileSize, FileSize, 0,
448                                   RequiresNullTerminator, IsVolatileSize);
449   Result = std::move(MB);
450   return ec;
451 }
452
453 error_code MemoryBuffer::getOpenFileSlice(int FD, const char *Filename,
454                                           std::unique_ptr<MemoryBuffer> &Result,
455                                           uint64_t MapSize, int64_t Offset,
456                                           bool IsVolatileSize) {
457   return getOpenFileImpl(FD, Filename, Result, -1, MapSize, Offset, false,
458                          IsVolatileSize);
459 }
460
461 error_code MemoryBuffer::getOpenFileSlice(int FD, const char *Filename,
462                                           OwningPtr<MemoryBuffer> &Result,
463                                           uint64_t MapSize, int64_t Offset,
464                                           bool IsVolatileSize) {
465   std::unique_ptr<MemoryBuffer> MB;
466   error_code ec = getOpenFileImpl(FD, Filename, MB, -1, MapSize, Offset, false,
467                                   IsVolatileSize);
468   Result = std::move(MB);
469   return ec;
470 }
471
472 //===----------------------------------------------------------------------===//
473 // MemoryBuffer::getSTDIN implementation.
474 //===----------------------------------------------------------------------===//
475
476 error_code MemoryBuffer::getSTDIN(std::unique_ptr<MemoryBuffer> &Result) {
477   // Read in all of the data from stdin, we cannot mmap stdin.
478   //
479   // FIXME: That isn't necessarily true, we should try to mmap stdin and
480   // fallback if it fails.
481   sys::ChangeStdinToBinary();
482
483   return getMemoryBufferForStream(0, "<stdin>", Result);
484 }
485
486 error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &Result) {
487   std::unique_ptr<MemoryBuffer> MB;
488   error_code ec = getSTDIN(MB);
489   Result = std::move(MB);
490   return ec;
491 }