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