Don't compute the file size if we don't need to.
[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/Support/MathExtras.h"
18 #include "llvm/Support/Errno.h"
19 #include "llvm/Support/Path.h"
20 #include "llvm/Support/Process.h"
21 #include "llvm/Support/Program.h"
22 #include "llvm/Support/system_error.h"
23 #include <cassert>
24 #include <cstdio>
25 #include <cstring>
26 #include <cerrno>
27 #include <new>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #if !defined(_MSC_VER) && !defined(__MINGW32__)
31 #include <unistd.h>
32 #include <sys/uio.h>
33 #else
34 #include <io.h>
35 #endif
36 #include <fcntl.h>
37 using namespace llvm;
38
39 namespace { const llvm::error_code success; }
40
41 //===----------------------------------------------------------------------===//
42 // MemoryBuffer implementation itself.
43 //===----------------------------------------------------------------------===//
44
45 MemoryBuffer::~MemoryBuffer() { }
46
47 /// init - Initialize this MemoryBuffer as a reference to externally allocated
48 /// memory, memory that we know is already null terminated.
49 void MemoryBuffer::init(const char *BufStart, const char *BufEnd,
50                         bool RequiresNullTerminator) {
51   assert((BufEnd[0] == 0 || !RequiresNullTerminator) &&
52          "Buffer is not null terminated!");
53   BufferStart = BufStart;
54   BufferEnd = BufEnd;
55 }
56
57 //===----------------------------------------------------------------------===//
58 // MemoryBufferMem implementation.
59 //===----------------------------------------------------------------------===//
60
61 /// CopyStringRef - Copies contents of a StringRef into a block of memory and
62 /// null-terminates it.
63 static void CopyStringRef(char *Memory, StringRef Data) {
64   memcpy(Memory, Data.data(), Data.size());
65   Memory[Data.size()] = 0; // Null terminate string.
66 }
67
68 /// GetNamedBuffer - Allocates a new MemoryBuffer with Name copied after it.
69 template <typename T>
70 static T* GetNamedBuffer(StringRef Buffer, StringRef Name,
71                          bool RequiresNullTerminator) {
72   char *Mem = static_cast<char*>(operator new(sizeof(T) + Name.size() + 1));
73   CopyStringRef(Mem + sizeof(T), Name);
74   return new (Mem) T(Buffer, RequiresNullTerminator);
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   virtual const char *getBufferIdentifier() const {
86      // The name is stored after the class itself.
87     return reinterpret_cast<const char*>(this + 1);
88   }
89 };
90 }
91
92 /// getMemBuffer - Open the specified memory range as a MemoryBuffer.  Note
93 /// that EndPtr[0] must be a null byte and be accessible!
94 MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
95                                          StringRef BufferName) {
96   return GetNamedBuffer<MemoryBufferMem>(InputData, BufferName, true);
97 }
98
99 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
100 /// copying the contents and taking ownership of it.  This has no requirements
101 /// on EndPtr[0].
102 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
103                                              StringRef BufferName) {
104   MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
105   if (!Buf) return 0;
106   memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
107          InputData.size());
108   return Buf;
109 }
110
111 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
112 /// that is not initialized.  Note that the caller should initialize the
113 /// memory allocated by this method.  The memory is owned by the MemoryBuffer
114 /// object.
115 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
116                                                   StringRef BufferName) {
117   // Allocate space for the MemoryBuffer, the data and the name. It is important
118   // that MemoryBuffer and data are aligned so PointerIntPair works with them.
119   size_t AlignedStringLen =
120     RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1,
121                        sizeof(void*)); // TODO: Is sizeof(void*) enough?
122   size_t RealLen = AlignedStringLen + Size + 1;
123   char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
124   if (!Mem) return 0;
125
126   // The name is stored after the class itself.
127   CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
128
129   // The buffer begins after the name and must be aligned.
130   char *Buf = Mem + AlignedStringLen;
131   Buf[Size] = 0; // Null terminate buffer.
132
133   return new (Mem) MemoryBufferMem(StringRef(Buf, Size), true);
134 }
135
136 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
137 /// is completely initialized to zeros.  Note that the caller should
138 /// initialize the memory allocated by this method.  The memory is owned by
139 /// the MemoryBuffer object.
140 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
141   MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
142   if (!SB) return 0;
143   memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
144   return SB;
145 }
146
147
148 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
149 /// if the Filename is "-".  If an error occurs, this returns null and fills
150 /// in *ErrStr with a reason.  If stdin is empty, this API (unlike getSTDIN)
151 /// returns an empty buffer.
152 error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
153                                         OwningPtr<MemoryBuffer> &result,
154                                         int64_t FileSize) {
155   if (Filename == "-")
156     return getSTDIN(result);
157   return getFile(Filename, result, FileSize);
158 }
159
160 error_code MemoryBuffer::getFileOrSTDIN(const char *Filename,
161                                         OwningPtr<MemoryBuffer> &result,
162                                         int64_t FileSize) {
163   if (strcmp(Filename, "-") == 0)
164     return getSTDIN(result);
165   return getFile(Filename, result, FileSize);
166 }
167
168 //===----------------------------------------------------------------------===//
169 // MemoryBuffer::getFile implementation.
170 //===----------------------------------------------------------------------===//
171
172 namespace {
173 /// MemoryBufferMMapFile - This represents a file that was mapped in with the
174 /// sys::Path::MapInFilePages method.  When destroyed, it calls the
175 /// sys::Path::UnMapFilePages method.
176 class MemoryBufferMMapFile : public MemoryBufferMem {
177 public:
178   MemoryBufferMMapFile(StringRef Buffer, bool RequiresNullTerminator)
179     : MemoryBufferMem(Buffer, RequiresNullTerminator) { }
180
181   ~MemoryBufferMMapFile() {
182     static int PageSize = sys::Process::GetPageSize();
183
184     uintptr_t Start = reinterpret_cast<uintptr_t>(getBufferStart());
185     size_t Size = getBufferSize();
186     uintptr_t RealStart = Start & ~(PageSize - 1);
187     size_t RealSize = Size + (Start - RealStart);
188
189     sys::Path::UnMapFilePages(reinterpret_cast<const char*>(RealStart),
190                               RealSize);
191   }
192 };
193 }
194
195 error_code MemoryBuffer::getFile(StringRef Filename,
196                                  OwningPtr<MemoryBuffer> &result,
197                                  int64_t FileSize) {
198   // Ensure the path is null terminated.
199   SmallString<256> PathBuf(Filename.begin(), Filename.end());
200   return MemoryBuffer::getFile(PathBuf.c_str(), result, FileSize);
201 }
202
203 error_code MemoryBuffer::getFile(const char *Filename,
204                                  OwningPtr<MemoryBuffer> &result,
205                                  int64_t FileSize) {
206   int OpenFlags = O_RDONLY;
207 #ifdef O_BINARY
208   OpenFlags |= O_BINARY;  // Open input file in binary mode on win32.
209 #endif
210   int FD = ::open(Filename, OpenFlags);
211   if (FD == -1) {
212     return error_code(errno, posix_category());
213   }
214   error_code ret = getOpenFile(FD, Filename, result, FileSize);
215   close(FD);
216   return ret;
217 }
218
219 static bool shouldUseMmap(int FD,
220                           size_t FileSize,
221                           size_t MapSize,
222                           off_t Offset,
223                           bool RequiresNullTerminator,
224                           int PageSize) {
225   // We don't use mmap for small files because this can severely fragment our
226   // address space.
227   if (MapSize < 4096*4)
228     return false;
229
230   if (!RequiresNullTerminator)
231     return true;
232
233
234   // If we don't know the file size, use fstat to find out.  fstat on an open
235   // file descriptor is cheaper than stat on a random path.
236   // FIXME: this chunk of code is duplicated, but it avoids a fstat when
237   // RequiresNullTerminator = false and MapSize != -1.
238   if (FileSize == size_t(-1)) {
239     struct stat FileInfo;
240     // TODO: This should use fstat64 when available.
241     if (fstat(FD, &FileInfo) == -1) {
242       return error_code(errno, posix_category());
243     }
244     FileSize = FileInfo.st_size;
245   }
246
247   // If we need a null terminator and the end of the map is inside the file,
248   // we cannot use mmap.
249   size_t End = Offset + MapSize;
250   assert(End <= FileSize);
251   if (End != FileSize)
252     return false;
253
254   // Don't try to map files that are exactly a multiple of the system page size
255   // if we need a null terminator.
256   if ((FileSize & (PageSize -1)) == 0)
257     return false;
258
259   return true;
260 }
261
262 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
263                                      OwningPtr<MemoryBuffer> &result,
264                                      size_t FileSize, size_t MapSize,
265                                      off_t Offset,
266                                      bool RequiresNullTerminator) {
267   static int PageSize = sys::Process::GetPageSize();
268
269   // Default is to map the full file.
270   if (MapSize == size_t(-1)) {
271     // If we don't know the file size, use fstat to find out.  fstat on an open
272     // file descriptor is cheaper than stat on a random path.
273     if (FileSize == size_t(-1)) {
274       struct stat FileInfo;
275       // TODO: This should use fstat64 when available.
276       if (fstat(FD, &FileInfo) == -1) {
277         return error_code(errno, posix_category());
278       }
279       FileSize = FileInfo.st_size;
280     }
281     MapSize = FileSize;
282   }
283
284   if (shouldUseMmap(FD, FileSize, MapSize, Offset, RequiresNullTerminator,
285                     PageSize)) {
286     off_t RealMapOffset = Offset & ~(PageSize - 1);
287     off_t Delta = Offset - RealMapOffset;
288     size_t RealMapSize = MapSize + Delta;
289
290     if (const char *Pages = sys::Path::MapInFilePages(FD,
291                                                       RealMapSize,
292                                                       RealMapOffset)) {
293       result.reset(GetNamedBuffer<MemoryBufferMMapFile>(
294           StringRef(Pages + Delta, MapSize), Filename, RequiresNullTerminator));
295       return success;
296     }
297   }
298
299   MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
300   if (!Buf) {
301     // Failed to create a buffer. The only way it can fail is if
302     // new(std::nothrow) returns 0.
303     return make_error_code(errc::not_enough_memory);
304   }
305
306   OwningPtr<MemoryBuffer> SB(Buf);
307   char *BufPtr = const_cast<char*>(SB->getBufferStart());
308
309   size_t BytesLeft = MapSize;
310   if (lseek(FD, Offset, SEEK_SET) == -1)
311     return error_code(errno, posix_category());
312
313   while (BytesLeft) {
314     ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
315     if (NumRead == -1) {
316       if (errno == EINTR)
317         continue;
318       // Error while reading.
319       return error_code(errno, posix_category());
320     } else if (NumRead == 0) {
321       // We hit EOF early, truncate and terminate buffer.
322       Buf->BufferEnd = BufPtr;
323       *BufPtr = 0;
324       result.swap(SB);
325       return success;
326     }
327     BytesLeft -= NumRead;
328     BufPtr += NumRead;
329   }
330
331   result.swap(SB);
332   return success;
333 }
334
335 //===----------------------------------------------------------------------===//
336 // MemoryBuffer::getSTDIN implementation.
337 //===----------------------------------------------------------------------===//
338
339 error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &result) {
340   // Read in all of the data from stdin, we cannot mmap stdin.
341   //
342   // FIXME: That isn't necessarily true, we should try to mmap stdin and
343   // fallback if it fails.
344   sys::Program::ChangeStdinToBinary();
345
346   const ssize_t ChunkSize = 4096*4;
347   SmallString<ChunkSize> Buffer;
348   ssize_t ReadBytes;
349   // Read into Buffer until we hit EOF.
350   do {
351     Buffer.reserve(Buffer.size() + ChunkSize);
352     ReadBytes = read(0, Buffer.end(), ChunkSize);
353     if (ReadBytes == -1) {
354       if (errno == EINTR) continue;
355       return error_code(errno, posix_category());
356     }
357     Buffer.set_size(Buffer.size() + ReadBytes);
358   } while (ReadBytes != 0);
359
360   result.reset(getMemBufferCopy(Buffer, "<stdin>"));
361   return success;
362 }