Merge System into Support.
[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 <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   // Ensure the path is null terminated.
191   SmallString<256> PathBuf(Filename.begin(), Filename.end());
192   return MemoryBuffer::getFile(PathBuf.c_str(), ErrStr, FileSize);
193 }
194
195 MemoryBuffer *MemoryBuffer::getFile(const char *Filename, std::string *ErrStr,
196                                     int64_t FileSize) {
197   int OpenFlags = O_RDONLY;
198 #ifdef O_BINARY
199   OpenFlags |= O_BINARY;  // Open input file in binary mode on win32.
200 #endif
201   int FD = ::open(Filename, OpenFlags);
202   if (FD == -1) {
203     if (ErrStr) *ErrStr = sys::StrError();
204     return 0;
205   }
206
207   return getOpenFile(FD, Filename, ErrStr, FileSize);
208 }
209
210 MemoryBuffer *MemoryBuffer::getOpenFile(int FD, const char *Filename,
211                                         std::string *ErrStr, int64_t FileSize) {
212   FileCloser FC(FD); // Close FD on return.
213
214   // If we don't know the file size, use fstat to find out.  fstat on an open
215   // file descriptor is cheaper than stat on a random path.
216   if (FileSize == -1) {
217     struct stat FileInfo;
218     // TODO: This should use fstat64 when available.
219     if (fstat(FD, &FileInfo) == -1) {
220       if (ErrStr) *ErrStr = sys::StrError();
221       return 0;
222     }
223     FileSize = FileInfo.st_size;
224   }
225
226
227   // If the file is large, try to use mmap to read it in.  We don't use mmap
228   // for small files, because this can severely fragment our address space. Also
229   // don't try to map files that are exactly a multiple of the system page size,
230   // as the file would not have the required null terminator.
231   //
232   // FIXME: Can we just mmap an extra page in the latter case?
233   if (FileSize >= 4096*4 &&
234       (FileSize & (sys::Process::GetPageSize()-1)) != 0) {
235     if (const char *Pages = sys::Path::MapInFilePages(FD, FileSize)) {
236       return GetNamedBuffer<MemoryBufferMMapFile>(StringRef(Pages, FileSize),
237                                                   Filename);
238     }
239   }
240
241   MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(FileSize, Filename);
242   if (!Buf) {
243     // Failed to create a buffer.
244     if (ErrStr) *ErrStr = "could not allocate buffer";
245     return 0;
246   }
247
248   OwningPtr<MemoryBuffer> SB(Buf);
249   char *BufPtr = const_cast<char*>(SB->getBufferStart());
250
251   size_t BytesLeft = FileSize;
252   while (BytesLeft) {
253     ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
254     if (NumRead == -1) {
255       if (errno == EINTR)
256         continue;
257       // Error while reading.
258       if (ErrStr) *ErrStr = sys::StrError();
259       return 0;
260     } else if (NumRead == 0) {
261       // We hit EOF early, truncate and terminate buffer.
262       Buf->BufferEnd = BufPtr;
263       *BufPtr = 0;
264       return SB.take();
265     }
266     BytesLeft -= NumRead;
267     BufPtr += NumRead;
268   }
269
270   return SB.take();
271 }
272
273 //===----------------------------------------------------------------------===//
274 // MemoryBuffer::getSTDIN implementation.
275 //===----------------------------------------------------------------------===//
276
277 MemoryBuffer *MemoryBuffer::getSTDIN(std::string *ErrStr) {
278   // Read in all of the data from stdin, we cannot mmap stdin.
279   //
280   // FIXME: That isn't necessarily true, we should try to mmap stdin and
281   // fallback if it fails.
282   sys::Program::ChangeStdinToBinary();
283
284   const ssize_t ChunkSize = 4096*4;
285   SmallString<ChunkSize> Buffer;
286   ssize_t ReadBytes;
287   // Read into Buffer until we hit EOF.
288   do {
289     Buffer.reserve(Buffer.size() + ChunkSize);
290     ReadBytes = read(0, Buffer.end(), ChunkSize);
291     if (ReadBytes == -1) {
292       if (errno == EINTR) continue;
293       if (ErrStr) *ErrStr = sys::StrError();
294       return 0;
295     }
296     Buffer.set_size(Buffer.size() + ReadBytes);
297   } while (ReadBytes != 0);
298
299   return getMemBufferCopy(Buffer, "<stdin>");
300 }