Add support for MemoryBuffers that are not null terminated and add
[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(size_t FileSize,
220                           size_t MapSize,
221                           off_t Offset,
222                           bool RequiresNullTerminator,
223                           int PageSize) {
224   // We don't use mmap for small files because this can severely fragment our
225   // address space.
226   if (MapSize < 4096*4)
227     return false;
228
229   if (!RequiresNullTerminator)
230     return true;
231
232   // If we need a null terminator and the end of the map is inside the file,
233   // we cannot use mmap.
234   size_t End = Offset + MapSize;
235   assert(End <= FileSize);
236   if (End != FileSize)
237     return false;
238
239   // Don't try to map files that are exactly a multiple of the system page size
240   // if we need a null terminator.
241   if ((FileSize & (PageSize -1)) == 0)
242     return false;
243
244   return true;
245 }
246
247 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
248                                      OwningPtr<MemoryBuffer> &result,
249                                      size_t FileSize, size_t MapSize,
250                                      off_t Offset,
251                                      bool RequiresNullTerminator) {
252   static int PageSize = sys::Process::GetPageSize();
253
254   // If we don't know the file size, use fstat to find out.  fstat on an open
255   // file descriptor is cheaper than stat on a random path.
256   if (FileSize == size_t(-1)) {
257     struct stat FileInfo;
258     // TODO: This should use fstat64 when available.
259     if (fstat(FD, &FileInfo) == -1) {
260       return error_code(errno, posix_category());
261     }
262     FileSize = FileInfo.st_size;
263   }
264
265   // Default is to map the full file.
266   if (MapSize == size_t(-1))
267     MapSize = FileSize;
268
269   if (shouldUseMmap(FileSize, MapSize, Offset, RequiresNullTerminator,
270                     PageSize)) {
271     off_t RealMapOffset = Offset & ~(PageSize - 1);
272     off_t Delta = Offset - RealMapOffset;
273     size_t RealMapSize = MapSize + Delta;
274
275     if (const char *Pages = sys::Path::MapInFilePages(FD,
276                                                       RealMapSize,
277                                                       RealMapOffset)) {
278       result.reset(GetNamedBuffer<MemoryBufferMMapFile>(
279           StringRef(Pages + Delta, MapSize), Filename, RequiresNullTerminator));
280       return success;
281     }
282   }
283
284   MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(MapSize, Filename);
285   if (!Buf) {
286     // Failed to create a buffer. The only way it can fail is if
287     // new(std::nothrow) returns 0.
288     return make_error_code(errc::not_enough_memory);
289   }
290
291   OwningPtr<MemoryBuffer> SB(Buf);
292   char *BufPtr = const_cast<char*>(SB->getBufferStart());
293
294   size_t BytesLeft = MapSize;
295   if (lseek(FD, Offset, SEEK_SET) == -1)
296     return error_code(errno, posix_category());
297
298   while (BytesLeft) {
299     ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
300     if (NumRead == -1) {
301       if (errno == EINTR)
302         continue;
303       // Error while reading.
304       return error_code(errno, posix_category());
305     } else if (NumRead == 0) {
306       // We hit EOF early, truncate and terminate buffer.
307       Buf->BufferEnd = BufPtr;
308       *BufPtr = 0;
309       result.swap(SB);
310       return success;
311     }
312     BytesLeft -= NumRead;
313     BufPtr += NumRead;
314   }
315
316   result.swap(SB);
317   return success;
318 }
319
320 //===----------------------------------------------------------------------===//
321 // MemoryBuffer::getSTDIN implementation.
322 //===----------------------------------------------------------------------===//
323
324 error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &result) {
325   // Read in all of the data from stdin, we cannot mmap stdin.
326   //
327   // FIXME: That isn't necessarily true, we should try to mmap stdin and
328   // fallback if it fails.
329   sys::Program::ChangeStdinToBinary();
330
331   const ssize_t ChunkSize = 4096*4;
332   SmallString<ChunkSize> Buffer;
333   ssize_t ReadBytes;
334   // Read into Buffer until we hit EOF.
335   do {
336     Buffer.reserve(Buffer.size() + ChunkSize);
337     ReadBytes = read(0, Buffer.end(), ChunkSize);
338     if (ReadBytes == -1) {
339       if (errno == EINTR) continue;
340       return error_code(errno, posix_category());
341     }
342     Buffer.set_size(Buffer.size() + ReadBytes);
343   } while (ReadBytes != 0);
344
345   result.reset(getMemBufferCopy(Buffer, "<stdin>"));
346   return success;
347 }