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