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