Remove the MappedFile::charBase member, rename base -> getBase() and
[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/System/MappedFile.h"
16 #include "llvm/System/Process.h"
17 #include "llvm/System/Program.h"
18 #include <cassert>
19 #include <cstdio>
20 #include <cstring>
21 #include <cerrno>
22 using namespace llvm;
23
24 //===----------------------------------------------------------------------===//
25 // MemoryBuffer implementation itself.
26 //===----------------------------------------------------------------------===//
27
28 MemoryBuffer::~MemoryBuffer() {
29   if (MustDeleteBuffer)
30     delete [] BufferStart;
31 }
32
33 /// initCopyOf - Initialize this source buffer with a copy of the specified
34 /// memory range.  We make the copy so that we can null terminate it
35 /// successfully.
36 void MemoryBuffer::initCopyOf(const char *BufStart, const char *BufEnd) {
37   size_t Size = BufEnd-BufStart;
38   BufferStart = new char[Size+1];
39   BufferEnd = BufferStart+Size;
40   memcpy(const_cast<char*>(BufferStart), BufStart, Size);
41   *const_cast<char*>(BufferEnd) = 0;   // Null terminate buffer.
42   MustDeleteBuffer = true;
43 }
44
45 /// init - Initialize this MemoryBuffer as a reference to externally allocated
46 /// memory, memory that we know is already null terminated.
47 void MemoryBuffer::init(const char *BufStart, const char *BufEnd) {
48   assert(BufEnd[0] == 0 && "Buffer is not null terminated!");
49   BufferStart = BufStart;
50   BufferEnd = BufEnd;
51   MustDeleteBuffer = false;
52 }
53
54 //===----------------------------------------------------------------------===//
55 // MemoryBufferMem implementation.
56 //===----------------------------------------------------------------------===//
57
58 namespace {
59 class MemoryBufferMem : public MemoryBuffer {
60   std::string FileID;
61 public:
62   MemoryBufferMem(const char *Start, const char *End, const char *FID,
63                   bool Copy = false)
64   : FileID(FID) {
65     if (!Copy)
66       init(Start, End);
67     else
68       initCopyOf(Start, End);
69   }
70   
71   virtual const char *getBufferIdentifier() const {
72     return FileID.c_str();
73   }
74 };
75 }
76
77 /// getMemBuffer - Open the specified memory range as a MemoryBuffer.  Note
78 /// that EndPtr[0] must be a null byte and be accessible!
79 MemoryBuffer *MemoryBuffer::getMemBuffer(const char *StartPtr, 
80                                          const char *EndPtr,
81                                          const char *BufferName) {
82   return new MemoryBufferMem(StartPtr, EndPtr, BufferName);
83 }
84
85 /// getMemBufferCopy - Open the specified memory range as a MemoryBuffer,
86 /// copying the contents and taking ownership of it.  This has no requirements
87 /// on EndPtr[0].
88 MemoryBuffer *MemoryBuffer::getMemBufferCopy(const char *StartPtr, 
89                                              const char *EndPtr,
90                                              const char *BufferName) {
91   return new MemoryBufferMem(StartPtr, EndPtr, BufferName, true);
92 }
93
94 /// getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size
95 /// that is completely initialized to zeros.  Note that the caller should
96 /// initialize the memory allocated by this method.  The memory is owned by
97 /// the MemoryBuffer object.
98 MemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(unsigned Size,
99                                                   const char *BufferName) {
100   char *Buf = new char[Size+1];
101   Buf[Size] = 0;
102   MemoryBufferMem *SB = new MemoryBufferMem(Buf, Buf+Size, BufferName);
103   // The memory for this buffer is owned by the MemoryBuffer.
104   SB->MustDeleteBuffer = true;
105   return SB;
106 }
107
108 /// getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that
109 /// is completely initialized to zeros.  Note that the caller should
110 /// initialize the memory allocated by this method.  The memory is owned by
111 /// the MemoryBuffer object.
112 MemoryBuffer *MemoryBuffer::getNewMemBuffer(unsigned Size,
113                                             const char *BufferName) {
114   MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);
115   memset(const_cast<char*>(SB->getBufferStart()), 0, Size+1);
116   return SB;
117 }
118
119
120 /// getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin
121 /// if the Filename is "-".  If an error occurs, this returns null and fills
122 /// in *ErrStr with a reason.  If stdin is empty, this API (unlike getSTDIN)
123 /// returns an empty buffer.
124 MemoryBuffer *MemoryBuffer::getFileOrSTDIN(const char *FilenameStart,
125                                            unsigned FnSize,
126                                            std::string *ErrStr,
127                                            int64_t FileSize) {
128   if (FnSize != 1 || FilenameStart[0] != '-')
129     return getFile(FilenameStart, FnSize, ErrStr, FileSize);
130   MemoryBuffer *M = getSTDIN();
131   if (M) return M;
132
133   // If stdin was empty, M is null.  Cons up an empty memory buffer now.
134   const char *EmptyStr = "";
135   return MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<stdin>");
136 }
137
138 //===----------------------------------------------------------------------===//
139 // MemoryBufferMMapFile implementation.
140 //===----------------------------------------------------------------------===//
141
142 namespace {
143 class MemoryBufferMMapFile : public MemoryBuffer {
144   sys::MappedFile File;
145 public:
146   MemoryBufferMMapFile() {}
147   
148   bool open(const sys::Path &Filename, std::string *ErrStr);
149   
150   virtual const char *getBufferIdentifier() const {
151     return File.path().c_str();
152   }
153     
154   ~MemoryBufferMMapFile();
155 };
156 }
157
158 bool MemoryBufferMMapFile::open(const sys::Path &Filename,
159                                 std::string *ErrStr) {
160   // FIXME: This does an extra stat syscall to figure out the size, but we
161   // already know the size!
162   bool Failure = File.open(Filename, ErrStr);
163   if (Failure) return true;
164   
165   if (!File.map(ErrStr))
166     return true;
167   
168   size_t Size = File.size();
169   
170   static unsigned PageSize = sys::Process::GetPageSize();
171   assert(((PageSize & (PageSize-1)) == 0) && PageSize &&
172          "Page size is not a power of 2!");
173   
174   // If this file is not an exact multiple of the system page size (common
175   // case), then the OS has zero terminated the buffer for us.
176   const char *FileBase = static_cast<const char*>(File.getBase());
177   if ((Size & (PageSize-1)) != 0) {
178     init(FileBase, FileBase+Size);
179   } else {
180     // Otherwise, we allocate a new memory buffer and copy the data over
181     initCopyOf(FileBase, FileBase+Size);
182     
183     // No need to keep the file mapped any longer.
184     File.unmap();
185   }
186   return false;
187 }
188
189 MemoryBufferMMapFile::~MemoryBufferMMapFile() {
190   if (File.isMapped())
191     File.unmap();
192 }
193
194 //===----------------------------------------------------------------------===//
195 // MemoryBuffer::getFile implementation.
196 //===----------------------------------------------------------------------===//
197
198 MemoryBuffer *MemoryBuffer::getFile(const char *FilenameStart, unsigned FnSize,
199                                     std::string *ErrStr, int64_t FileSize){
200   // FIXME: it would be nice if PathWithStatus didn't copy the filename into a
201   // temporary string. :(
202   sys::PathWithStatus P(FilenameStart, FnSize);
203 #if 1
204   MemoryBufferMMapFile *M = new MemoryBufferMMapFile();
205   if (!M->open(P, ErrStr))
206     return M;
207   delete M;
208   return 0;
209 #else
210   // FIXME: We need an efficient and portable method to open a file and then use
211   // 'read' to copy the bits out.  The unix implementation is below.  This is
212   // an important optimization for clients that want to open large numbers of
213   // small files (using mmap on everything can easily exhaust address space!).
214   
215   // If the user didn't specify a filesize, do a stat to find it.
216   if (FileSize == -1) {
217     const sys::FileStatus *FS = P.getFileStatus();
218     if (FS == 0) return 0;  // Error stat'ing file.
219    
220     FileSize = FS->fileSize;
221   }
222   
223   // If the file is larger than some threshold, use mmap, otherwise use 'read'.
224   if (FileSize >= 4096*4) {
225     MemoryBufferMMapFile *M = new MemoryBufferMMapFile();
226     if (!M->open(P, ErrStr))
227       return M;
228     delete M;
229     return 0;
230   }
231   
232   MemoryBuffer *SB = getNewUninitMemBuffer(FileSize, FilenameStart);
233   char *BufPtr = const_cast<char*>(SB->getBufferStart());
234   
235   int FD = ::open(FilenameStart, O_RDONLY);
236   if (FD == -1) {
237     delete SB;
238     return 0;
239   }
240   
241   unsigned BytesLeft = FileSize;
242   while (BytesLeft) {
243     ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);
244     if (NumRead != -1) {
245       BytesLeft -= NumRead;
246       BufPtr += NumRead;
247     } else if (errno == EINTR) {
248       // try again
249     } else {
250       // error reading.
251       close(FD);
252       delete SB;
253       return 0;
254     }
255   }
256   close(FD);
257   
258   return SB;
259 #endif
260 }
261
262
263 //===----------------------------------------------------------------------===//
264 // MemoryBuffer::getSTDIN implementation.
265 //===----------------------------------------------------------------------===//
266
267 namespace {
268 class STDINBufferFile : public MemoryBuffer {
269 public:
270   virtual const char *getBufferIdentifier() const {
271     return "<stdin>";
272   }
273 };
274 }
275
276 MemoryBuffer *MemoryBuffer::getSTDIN() {
277   char Buffer[4096*4];
278   
279   std::vector<char> FileData;
280   
281   // Read in all of the data from stdin, we cannot mmap stdin.
282   sys::Program::ChangeStdinToBinary();
283   while (size_t ReadBytes = fread(Buffer, sizeof(char), 4096*4, stdin))
284     FileData.insert(FileData.end(), Buffer, Buffer+ReadBytes);
285
286   FileData.push_back(0); // &FileData[Size] is invalid. So is &*FileData.end().
287   size_t Size = FileData.size();
288   if (Size <= 1)
289     return 0;
290   MemoryBuffer *B = new STDINBufferFile();
291   B->initCopyOf(&FileData[0], &FileData[Size-1]);
292   return B;
293 }