MemoryBuffer now return an error_code and returns a OwningPtr<MemoryBuffer> via an...
[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 <sys/types.h>
28 #include <sys/stat.h>
29 #if !defined(_MSC_VER) && !defined(__MINGW32__)
30 #include <unistd.h>
31 #include <sys/uio.h>
32 #else
33 #include <io.h>
34 #endif
35 #include <fcntl.h>
36 using namespace llvm;
37
38 namespace { const llvm::error_code success; }
39
40 //===----------------------------------------------------------------------===//
41 // MemoryBuffer implementation itself.
42 //===----------------------------------------------------------------------===//
43
44 MemoryBuffer::~MemoryBuffer() { }
45
46 /// init - Initialize this MemoryBuffer as a reference to externally allocated
47 /// memory, memory that we know is already null terminated.
48 void MemoryBuffer::init(const char *BufStart, const char *BufEnd) {
49   assert(BufEnd[0] == 0 && "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 /// GetNamedBuffer - Allocates a new MemoryBuffer with Name copied after it.
66 template <typename T>
67 static T* GetNamedBuffer(StringRef Buffer, StringRef Name) {
68   char *Mem = static_cast<char*>(operator new(sizeof(T) + Name.size() + 1));
69   CopyStringRef(Mem + sizeof(T), Name);
70   return new (Mem) T(Buffer);
71 }
72
73 namespace {
74 /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory.
75 class MemoryBufferMem : public MemoryBuffer {
76 public:
77   MemoryBufferMem(StringRef InputData) {
78     init(InputData.begin(), InputData.end());
79   }
80
81   virtual const char *getBufferIdentifier() const {
82      // The name is stored after the class itself.
83     return reinterpret_cast<const char*>(this + 1);
84   }
85 };
86 }
87
88 /// getMemBuffer - Open the specified memory range as a MemoryBuffer.  Note
89 /// that EndPtr[0] must be a null byte and be accessible!
90 MemoryBuffer *MemoryBuffer::getMemBuffer(StringRef InputData,
91                                          StringRef BufferName) {
92   return GetNamedBuffer<MemoryBufferMem>(InputData, BufferName);
93 }
94
95 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
96 /// copying the contents and taking ownership of it.  This has no requirements
97 /// on EndPtr[0].
98 MemoryBuffer *MemoryBuffer::getMemBufferCopy(StringRef InputData,
99                                              StringRef BufferName) {
100   MemoryBuffer *Buf = getNewUninitMemBuffer(InputData.size(), BufferName);
101   if (!Buf) return 0;
102   memcpy(const_cast<char*>(Buf->getBufferStart()), InputData.data(),
103          InputData.size());
104   return Buf;
105 }
106
107 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
108 /// that is not initialized.  Note that the caller should initialize the
109 /// memory allocated by this method.  The memory is owned by the MemoryBuffer
110 /// object.
111 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,
112                                                   StringRef BufferName) {
113   // Allocate space for the MemoryBuffer, the data and the name. It is important
114   // that MemoryBuffer and data are aligned so PointerIntPair works with them.
115   size_t AlignedStringLen =
116     RoundUpToAlignment(sizeof(MemoryBufferMem) + BufferName.size() + 1,
117                        sizeof(void*)); // TODO: Is sizeof(void*) enough?
118   size_t RealLen = AlignedStringLen + Size + 1;
119   char *Mem = static_cast<char*>(operator new(RealLen, std::nothrow));
120   if (!Mem) return 0;
121
122   // The name is stored after the class itself.
123   CopyStringRef(Mem + sizeof(MemoryBufferMem), BufferName);
124
125   // The buffer begins after the name and must be aligned.
126   char *Buf = Mem + AlignedStringLen;
127   Buf[Size] = 0; // Null terminate buffer.
128
129   return new (Mem) MemoryBufferMem(StringRef(Buf, Size));
130 }
131
132 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
133 /// is completely initialized to zeros.  Note that the caller should
134 /// initialize the memory allocated by this method.  The memory is owned by
135 /// the MemoryBuffer object.
136 MemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size, StringRef BufferName) {
137   MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
138   if (!SB) return 0;
139   memset(const_cast<char*>(SB->getBufferStart()), 0, Size);
140   return SB;
141 }
142
143
144 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
145 /// if the Filename is "-".  If an error occurs, this returns null and fills
146 /// in *ErrStr with a reason.  If stdin is empty, this API (unlike getSTDIN)
147 /// returns an empty buffer.
148 error_code MemoryBuffer::getFileOrSTDIN(StringRef Filename,
149                                         OwningPtr<MemoryBuffer> &result,
150                                         int64_t FileSize) {
151   if (Filename == "-")
152     return getSTDIN(result);
153   return getFile(Filename, result, FileSize);
154 }
155
156 error_code MemoryBuffer::getFileOrSTDIN(const char *Filename,
157                                         OwningPtr<MemoryBuffer> &result,
158                                         int64_t FileSize) {
159   if (strcmp(Filename, "-") == 0)
160     return getSTDIN(result);
161   return getFile(Filename, result, FileSize);
162 }
163
164 //===----------------------------------------------------------------------===//
165 // MemoryBuffer::getFile implementation.
166 //===----------------------------------------------------------------------===//
167
168 namespace {
169 /// MemoryBufferMMapFile - This represents a file that was mapped in with the
170 /// sys::Path::MapInFilePages method.  When destroyed, it calls the
171 /// sys::Path::UnMapFilePages method.
172 class MemoryBufferMMapFile : public MemoryBufferMem {
173 public:
174   MemoryBufferMMapFile(StringRef Buffer)
175     : MemoryBufferMem(Buffer) { }
176
177   ~MemoryBufferMMapFile() {
178     sys::Path::UnMapFilePages(getBufferStart(), getBufferSize());
179   }
180 };
181
182 /// FileCloser - RAII object to make sure an FD gets closed properly.
183 class FileCloser {
184   int FD;
185 public:
186   explicit FileCloser(int FD) : FD(FD) {}
187   ~FileCloser() { ::close(FD); }
188 };
189 }
190
191 error_code MemoryBuffer::getFile(StringRef Filename,
192                                  OwningPtr<MemoryBuffer> &result,
193                                  int64_t FileSize) {
194   // Ensure the path is null terminated.
195   SmallString<256> PathBuf(Filename.begin(), Filename.end());
196   return MemoryBuffer::getFile(PathBuf.c_str(), result, FileSize);
197 }
198
199 error_code MemoryBuffer::getFile(const char *Filename,
200                                  OwningPtr<MemoryBuffer> &result,
201                                  int64_t FileSize) {
202   int OpenFlags = O_RDONLY;
203 #ifdef O_BINARY
204   OpenFlags |= O_BINARY;  // Open input file in binary mode on win32.
205 #endif
206   int FD = ::open(Filename, OpenFlags);
207   if (FD == -1) {
208     return error_code(errno, posix_category());
209   }
210
211   return getOpenFile(FD, Filename, result, FileSize);
212 }
213
214 error_code MemoryBuffer::getOpenFile(int FD, const char *Filename,
215                                      OwningPtr<MemoryBuffer> &result,
216                                      int64_t FileSize) {
217   FileCloser FC(FD); // Close FD on return.
218
219   // If we don't know the file size, use fstat to find out.  fstat on an open
220   // file descriptor is cheaper than stat on a random path.
221   if (FileSize == -1) {
222     struct stat FileInfo;
223     // TODO: This should use fstat64 when available.
224     if (fstat(FD, &FileInfo) == -1) {
225       return error_code(errno, posix_category());
226     }
227     FileSize = FileInfo.st_size;
228   }
229
230
231   // If the file is large, try to use mmap to read it in.  We don't use mmap
232   // for small files, because this can severely fragment our address space. Also
233   // don't try to map files that are exactly a multiple of the system page size,
234   // as the file would not have the required null terminator.
235   //
236   // FIXME: Can we just mmap an extra page in the latter case?
237   if (FileSize >= 4096*4 &&
238       (FileSize & (sys::Process::GetPageSize()-1)) != 0) {
239     if (const char *Pages = sys::Path::MapInFilePages(FD, FileSize)) {
240       result.reset(GetNamedBuffer<MemoryBufferMMapFile>(
241         StringRef(Pages, FileSize), Filename));
242       return success;
243     }
244   }
245
246   MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(FileSize, Filename);
247   if (!Buf) {
248     // Failed to create a buffer. The only way it can fail is if
249     // new(std::nothrow) returns 0.
250     return make_error_code(errc::not_enough_memory);
251   }
252
253   OwningPtr<MemoryBuffer> SB(Buf);
254   char *BufPtr = const_cast<char*>(SB->getBufferStart());
255
256   size_t BytesLeft = FileSize;
257   while (BytesLeft) {
258     ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
259     if (NumRead == -1) {
260       if (errno == EINTR)
261         continue;
262       // Error while reading.
263       return error_code(errno, posix_category());
264     } else if (NumRead == 0) {
265       // We hit EOF early, truncate and terminate buffer.
266       Buf->BufferEnd = BufPtr;
267       *BufPtr = 0;
268       result.swap(SB);
269       return success;
270     }
271     BytesLeft -= NumRead;
272     BufPtr += NumRead;
273   }
274
275   result.swap(SB);
276   return success;
277 }
278
279 //===----------------------------------------------------------------------===//
280 // MemoryBuffer::getSTDIN implementation.
281 //===----------------------------------------------------------------------===//
282
283 error_code MemoryBuffer::getSTDIN(OwningPtr<MemoryBuffer> &result) {
284   // Read in all of the data from stdin, we cannot mmap stdin.
285   //
286   // FIXME: That isn't necessarily true, we should try to mmap stdin and
287   // fallback if it fails.
288   sys::Program::ChangeStdinToBinary();
289
290   const ssize_t ChunkSize = 4096*4;
291   SmallString<ChunkSize> Buffer;
292   ssize_t ReadBytes;
293   // Read into Buffer until we hit EOF.
294   do {
295     Buffer.reserve(Buffer.size() + ChunkSize);
296     ReadBytes = read(0, Buffer.end(), ChunkSize);
297     if (ReadBytes == -1) {
298       if (errno == EINTR) continue;
299       return error_code(errno, posix_category());
300     }
301     Buffer.set_size(Buffer.size() + ReadBytes);
302   } while (ReadBytes != 0);
303
304   result.reset(getMemBufferCopy(Buffer, "<stdin>"));
305   return success;
306 }